【发布时间】:2019-04-03 13:03:17
【问题描述】:
我有一个 Product 类,它是用代码构造的。此代码用于调用开放食品事实 API 以实例化所有类变量。事实上,API 调用是一个异步函数。所以在我的主线程中,当我尝试访问我的对象参数时,它是空的。由于我无法中断主线程,我想如何对我的对象实例化进行回调?
这里是代码
Product.kt
class Product(code: Long) {
val client = OkHttpClient()
var name: String? = null
var imageUrl: String? = null
var packerCode: Int? = null
var packerCity: String? = null
var lat: Int? = null
var long: Int? = null
init {
run("https://fr.openfoodfacts.org/api/v0/produit/$code.json")
}
private fun run(url: String) {
val request = Request.Builder()
.url(url)
.build()
client.newCall(request).enqueue(object : Callback {
override fun onFailure(call: Call?, e: IOException) {}
override fun onResponse(call: Call?, response: Response){
val jsonData = response.body()?.string()
val Jobject = JSONObject(jsonData)
name = Jobject.getJSONObject("product").getString("product_name")
}
})
}
}
GameActivity.kt
class GameActivity : AppCompatActivity(){
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_game)
val textView: TextView = findViewById(R.id.productName) as TextView
val product = Product(3564700014677)
// Product.name empty
textView.text = product.name
}
【问题讨论】:
标签: android api class asynchronous kotlin