Нужно получить "firstname" в MainActivity(Log, Toast). Как реализовать? На простом примере крашится приложение.
{"firstname":"Bob"}
package json.usage
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response
class MainActivity : AppCompatActivity() {
private val URL = "https://api.myjson.com/"
private var irest: IRest? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val retrofit = Retrofit.Builder()
.baseUrl(URL)
.addConverterFactory(GsonConverterFactory.create())
.build()
irest!!.getName().enqueue(object : Callback<Data> {
override fun onResponse(call: Call<Data>, response: Response<Data>) {
Log.e("<<<<", ">>>>")
}
override fun onFailure(call: Call<Data>?, t: Throwable?) {
TODO("not implemented")
}
})
}
}
package json.usage
class Data {
var firstname: String? = null
}
package json.usage
import retrofit2.Call
import retrofit2.http.GET
interface IRest {
@GET("bins/vytod/")
fun getName(): Call<Data>
}
10-03 11:31:53.146 15549-15549/? E/AndroidRuntime: FATAL EXCEPTION: main
Process: json.usage, PID: 15549
java.lang.RuntimeException: Unable to start activity ComponentInfo{json.usage/json.usage.MainActivity}: kotlin.KotlinNullPointerException
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2416)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476)
at android.app.ActivityThread.-wrap11(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5417)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
Caused by: kotlin.KotlinNullPointerException
at json.usage.MainActivity.onCreate(MainActivity.kt:28)
at android.app.Activity.performCreate(Activity.java:6237)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1107)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2369)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476)
at android.app.ActivityThread.-wrap11(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5417)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)