科特林 | API 使用 okhttp 请求

Kotlin | API request with okhttp

解决方案:

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()
            }
        }
    }
} ```

我的 api 请求有此代码,当我使用 debugger.

时它有效

我可以在 PlayerStats 中看到结果 class 但现在我遇到了问题。

但是在 MainActivity.class 上这个 function 不起作用:

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")
    }
})

Stats.class:

class PlayerStats(val username: String  , val level: Double )

我需要一种方法来从 MainActivity

访问 val username / val level
class MainActivity(val mystats: PlayerStats) : AppCompatActivity(){

Not works, because of the zero arguments.

如果我尝试修复:

class MyActivity: AppCompatActivity() {
    var myStats: Stats? = null
//..
}

IDE 说它需要一个 safe call 或一个 non-null asserted 调用,但是如果我用 non-null asserted 调用尝试这个应用程序崩溃,我得到这个错误:

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.invoke(MainActivity.kt:31) at my.example.package.MainActivity$onCreate.onClick(MainActivity.kt:68) at android.view.View.performClick(View.java:7125) at android.view.View.performClickInternal(View.java:7102) at android.view.View.access00(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)

使用 safe call 我得到 null 作为输出


完整代码:

MainActivity.class:

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()
            }
        }
    }
}

玩家Stats.class:

package my.example.package
class PlayerStats(val username: String  , val level: Double )

将此替换为您的代码:

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()
            }
        }
    }
} ```