简体   繁体   English

通过Kotlin中的匿名内部对象修改外部类

[英]modify outer class through anonymous inner object in kotlin

I'm writing my first Android app in Kotlin. 我正在用Kotlin编写我的第一个Android应用程序。

What I'm trying to do is to issue an HTTP request (Volley) in order to fetch some data which shall be written into the object's properties. 我要执行的操作是发出HTTP请求(Volley),以获取一些应写入对象属性的数据。
That works fine so far until the Volley response listener is left. 到目前为止,这种方法一直很好,直到没有Volley响应侦听器为止。 Afterwards the properties are back to null. 之后,属性将返回空。

This is the caller: 这是呼叫者:

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
    }
}

The callee: 被叫方:

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)
    }
}

It's probably an issue with the object's scope but I wasn't able to figure out why the values arn't preserved. 这可能是对象范围的问题,但我无法弄清楚为什么不保留这些值。 Thanks a lot for any kind for help! 非常感谢您的帮助!

The question was answered in the comments. 评论中回答了这个问题。 The HTTP request handn't returned yet when the show() method was called. 调用show()方法时,HTTP请求尚未返回。 I got confused by the debugger because it makes it look like it's already there. 调试器使我感到困惑,因为它使它看起来已经存在了。

Thanks @Chisko 谢谢@Chisko

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM