gpt4 book ai didi

android - 无法从 Kotlin Android 中解析的 Json 数据为 TextView 赋值

转载 作者:行者123 更新时间:2023-11-29 23:46:07 24 4
gpt4 key购买 nike

我有一个 textView,我想在其中存储来自 API 的数据。以下是我的代码

import android.os.Bundle
import android.support.v7.app.AppCompatActivity
import android.widget.Button
import android.widget.TextView
import com.google.gson.GsonBuilder
import okhttp3.*
import java.io.IOException


class MainActivity : AppCompatActivity() {


override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)

val btnFindIp = findViewById<Button>(R.id.btnFindIp)
val txtIP = findViewById<TextView>(R.id.txtIP)

btnFindIp.setOnClickListener {
fetchJsonData()
}


} //onCreate Ends here


fun fetchJsonData() {
val url = "https://ipapi.co/json/"
val request = Request.Builder().url(url).build()
val httpClient = OkHttpClient()
val txtIP = findViewById<TextView>(R.id.txtIP)



httpClient.newCall(request).enqueue(object : Callback {
override fun onFailure(call: Call?, e: IOException?) {
println("Failed to execute")
}

override fun onResponse(call: Call?, response: Response?) {
val body = response?.body()?.string()
val gson = GsonBuilder().create()
val ipData:Ip = gson.fromJson(body, Ip::class.java)
// txtIP.text = ipData.ip.toString()
println(ipData.country_name)

txtIP.text = ipData.ip

}
})


}


data class Ip(
val ip: String,
val city: String,
val region: String,
val region_code: Any,
val country: String,
val country_name: String,
val continent_code: String,
val in_eu: Boolean,
val postal: Any,
val latitude: Double,
val longitude: Double,
val timezone: Any,
val utc_offset: Any,
val country_calling_code: String,
val currency: String,
val languages: String,
val asn: String,
val org: String
)

}

我成功地从 API 获取数据并将其解析为 Data 类

 println(ipData.country_name)

这给出了正确的输出,但是当我将数据类值分配给 txtIP.text = ipData.ip 时,什么也没有发生,我确定我错过了一些东西,因为我对 Android 以及 Kotlin

非常感谢任何帮助

最佳答案

您不能从其他线程编辑 UI。自 documentation OkHTTP 说:

The recipient of the callback may consume the response body on another thread.

你必须这样设置文本:

runOnUiThread {txtIP.text = ipData.ip }

关于android - 无法从 Kotlin Android 中解析的 Json 数据为 TextView 赋值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51381857/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com