title: Kotlin | API request with okhttp
body: <p>Solution:</p>
  
  <pre><code>class MainActivity : AppCompatActivity() {
      lateinit var playerStats: PlayerStats
  
      override fun onCreate(savedInstanceState: Bundle?) {
          super.onCreate(savedInstanceState)
          setContentView(R.layout.activity_main)
          Picasso.get().load("https://...../....../example.png").into(Viewer)
          var PlayerName: String = ""
  
          fun fetchJson() {
              val url = "https://my.api.site/example/"
              val request = Request.Builder().url(url).build()
              val client = OkHttpClient()
              client.newCall(request).enqueue(object : Callback {
                  var mainHandler = Handler(this@MainActivity.getMainLooper())
                  override fun onResponse(call: Call, response: Response) {
                      mainHandler.post {
                          val body = response.body()?.string()
                          if (body == null) return@post
                          println(body)
  
                          val gson = GsonBuilder().create()
                          playerStats = gson.fromJson(body, PlayerStats::class.java)
                          println(playerStats)
  
                          // TODO Now you can access to your view and set every thing to textView
                          textView.text = playerStats.username
                      }
                  }
  
                  override fun onFailure(call: Call, e: IOException) {
                      println("API execute failed")
                  }
              })
          }
  
          buttonGO.setOnClickListener {
              PlayerName = editText.text.toString()
              fetchJson()
              if (PlayerName == null || PlayerName.trim() == "") {
                  println("please input data, input cannot be blank")
              } else {
                  Picasso.get().load("https://...../...../" + PlayerName + ".png")
                      .into(Viewer)
                  textView.setText(PlayerName).toString()
              }
          }
      }
  } ```
  </code></pre>
  
  <p>I have this code for my api request and it works when I use <strong>debugger</strong>.</p>
  
  <p>I can see the results in the PlayerStats class but now I have a problem. </p>
  
  <p>But on the <strong><code>MainActivity.class</code></strong> this <code>function</code> don't work:</p>
  
  <pre><code>val url = "https://api.example.com/..../"
  val request = Request.Builder().url(url).build()
  val client = OkHttpClient()
  
  client.newCall(request).enqueue(object: Callback {
      override fun onResponse(call: Call, response: Response) {
          val body = response?.body?.string()
          println(body)
          val gson = GsonBuilder().create()
          val PlayerStats = gson.fromJson(body, PlayerStats::class.java)
          println(PlayerStats)
      }
  
      override fun onFailure(call: Call, e: IOException) {
          println("API execute failed")
      }
  })
  </code></pre>
  
  <p><strong>Stats.class</strong>:</p>
  
  <pre><code>class PlayerStats(val username: String  , val level: Double )
  </code></pre>
  
  <p>I need a way to get access to the <code>val username</code> / <code>val level</code> from <code>MainActivity</code></p>
  
  <pre><code>class MainActivity(val mystats: PlayerStats) : AppCompatActivity(){
  </code></pre>
  
  <blockquote>
    <p>Not works, because of the zero arguments.</p>
  </blockquote>
  
  <p>If I try to fix:</p>
  
  <pre><code>class MyActivity: AppCompatActivity() {
      var myStats: Stats? = null
  //..
  }
  </code></pre>
  
  <p>The IDE say it needs a <code>safe call</code> or a <code>non-null</code> asserted call but if I try this with the <code>non-null</code> asserted call the application crash and i get this error:</p>
  
  <blockquote>
    <p>2020-03-05 18:58:02.803 23276-23276/my.example.package
    E/AndroidRuntime: 
        FATAL EXCEPTION: main
        Process: my.example.package, PID: 23276
        kotlin.KotlinNullPointerException
          at my.example.package.MainActivity$onCreate$1.invoke(MainActivity.kt:31)
          at my.example.package.MainActivity$onCreate$3.onClick(MainActivity.kt:68)
          at android.view.View.performClick(View.java:7125)
          at android.view.View.performClickInternal(View.java:7102)
          at android.view.View.access$3500(View.java:801)
          at android.view.View$PerformClick.run(View.java:27336)
          at android.os.Handler.handleCallback(Handler.java:883)
          at android.os.Handler.dispatchMessage(Handler.java:100)
          at android.os.Looper.loop(Looper.java:214)
          at android.app.ActivityThread.main(ActivityThread.java:7356)
          at java.lang.reflect.Method.invoke(Native Method)
          at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:492)
          at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:930)</p>
  </blockquote>
  
  <p>With the <code>safe call</code> I get <code>null</code> as output</p>
  
  <hr>
  
  <p><strong>Full code:</strong></p>
  
  <p>MainActivity.class:</p>
  
  <pre><code>package my.example.package
  
  import android.os.Bundle
  import androidx.appcompat.app.AppCompatActivity
  import com.google.gson.GsonBuilder
  import com.squareup.picasso.Picasso
  import kotlinx.android.synthetic.main.activity_main.*
  import okhttp3.OkHttpClient
  import okhttp3.Request
  import okhttp3.*
  import java.io.IOException
  
  class MainActivity : AppCompatActivity(){
      override fun onCreate(savedInstanceState: Bundle?) {
          super.onCreate(savedInstanceState)
          setContentView(R.layout.activity_main)
          Picasso.get().load("https://...../....../example.png").into(Viewer)
          var PlayerName: String = ""
          fun fetchJson() {
              val url = "https://my.api.site/example/"
              val request = Request.Builder().url(url).build()
              val client = OkHttpClient()
              client.newCall(request).enqueue(object: Callback {
                  override fun onResponse(call: Call, response: Response) {
                      val body = response?.body?.string()
                      println(body)
                      val gson = GsonBuilder().create()
                      val PlayerStats = gson.fromJson(body, PlayerStats::class.java)
                      println(PlayerStats)
                  }
                  override fun onFailure(call: Call, e: IOException) {
                      println("API execute failed")
                  }
              })
          }
  
          buttonGO.setOnClickListener {
              PlayerName = editText.text.toString()
              fetchJson()
              if (PlayerName == null || PlayerName.trim() == "") {
                  println("please input data, input cannot be blank")
              } else {
                  Picasso.get().load("https://...../...../" + PlayerName + ".png")
                      .into(Viewer)
                  textView.setText(PlayerName).toString()
              }
          }
      }
  }
  </code></pre>
  
  <p>PlayerStats.class:</p>
  
  <pre><code>package my.example.package
  class PlayerStats(val username: String  , val level: Double )
  </code></pre>