我正在用Kotlin写我的第一个Android应用程序。
我要做的是发出一个HTTP请求(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)
}
}这可能是对象的作用域的一个问题,但我无法弄清楚为什么arn值不被保留。非常感谢您的任何帮助!
发布于 2018-01-02 20:12:09
评论中回答了这个问题。当调用show()方法时,HTTP尚未返回。我被调试器搞糊涂了,因为它让我觉得它已经存在了。
谢谢@Chisko
https://stackoverflow.com/questions/48066986
复制相似问题