我有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都是陌生的
任何帮助将不胜感激
答案 0 :(得分:1)
您不能从其他线程编辑UI。由于OkHTTP的documentation说:
回调的接收者可能会在另一个线程上消耗响应主体。
您必须以这种方式设置文本:
@SuppressLint("RestrictedApi") // also suppressed the warning
private void setUp() {
....
}