【问题标题】:Cannot assign value to TextView from parsed Json data in Kotlin Android无法从 Kotlin Android 中解析的 Json 数据为 TextView 赋值
【发布时间】:2018-07-18 05:37:13
【问题描述】:

我有 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 都很陌生

任何帮助将不胜感激

【问题讨论】:

标签: android kotlin


【解决方案1】:

您无法从其他线程编辑 UI。由于 OkHTTP 的 documentation 说:

回调的接收者可能会在另一个线程上使用响应正文。

你必须以这种方式设置文本:

runOnUiThread {txtIP.text = ipData.ip }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-11-04
    • 2012-11-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多