我正在用Kotlin编写我的第一个Android应用程序。
我要执行的操作是发出HTTP请求(Volley),以获取一些应写入对象属性的数据。
到目前为止,这种方法一直很好,直到没有Volley响应侦听器为止。之后,属性将返回空。
这是呼叫者:
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
[email protected] = haiku["title"] as String // all properties look alright here
[email protected] = haiku["author"] as String
[email protected] = 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)
}
}
这可能是对象范围的问题,但我无法弄清楚为什么不保留这些值。非常感谢您的帮助!
评论中回答了这个问题。show()
调用该方法时,HTTP请求尚未返回。调试器使我感到困惑,因为它使它看起来已经存在了。
谢谢@Chisko
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句