我在Kotlin写了我的第一个Android应用程序。
我尝试做的是发出HTTP请求(Volley)以获取一些数据,这些数据应写入对象的属性。
到目前为止一直工作正常,直到Volley响应听众离开。之后,属性将返回null。
这是来电者:
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
val haiku = Haiku(applicationContext)
haiku.load() // populates 3 properties (author, body, title)
haiku.show() // author, body, title are back to null here
}
}
被叫方:
class Haiku(var context: Context? = null, var title: String? = null, var body: String? = null,
var author: String? = null) : Parcelable { // parcelable implementaion left out here
fun load() {
val stringRequest = object : StringRequest(Request.Method.GET, EndPoints.URL_GET_HAIKU,
Response.Listener { response ->
try {
val json = JSONObject(response) // proper payload arrives
val haiku = json["haiku"] as JSONObject
this@Haiku.title = haiku["title"] as String // all properties look alright here
this@Haiku.author = haiku["author"] as String
this@Haiku.body = haiku["body"] as String
} catch (e: JSONException) {
Toast.makeText(context, R.string.haiku_not_fetched,
Toast.LENGTH_LONG).show()
}
},
Response.ErrorListener { error ->
Toast.makeText(context, R.string.haiku_not_fetched,
Toast.LENGTH_LONG).show()
}) {
}
VolleySingleton.instance?.addToRequestQueue(stringRequest)
}
fun show() { // when called after the load method title, body, author are back to null
val intent = Intent(context, HaikuDisplayActivity::class.java)
intent.putExtra(EXTRA_HAIKU, this)
context!!.startActivity(intent)
}
}
这可能是对象范围的一个问题,但我无法弄清楚为什么价值观不被保留。非常感谢您的帮助!
答案 0 :(得分:0)
评论中回答了这个问题。调用show()
方法时,HTTP请求handn尚未返回。我对调试器感到困惑,因为它使它看起来已经存在了。
谢谢@Chisko