Kotlin视图绑定java.lang.IllegalStateException:侦听器内的视图不能为null [英] Kotlin View Binding java.lang.IllegalStateException: view must not be null inside listener

查看:168
本文介绍了Kotlin视图绑定java.lang.IllegalStateException:侦听器内的视图不能为null的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Kotlin Android的视图绑定扩展程序:

I'm using View Binding from Kotlin Android Extensions:

import kotlinx.android.synthetic.main.fragment_user_profile.*

我想在片段中显示Cloud Firestore的值:

I want to display a value from Cloud Firestore in a fragment:

FirebaseFirestore.getInstance()
    .collection("users")
    .document("1")
    .get()
    .addOnSuccessListener { doc ->
        my_text_view.text = doc["name"] as String
    }

如果在接收数据时仍显示该片段,则它起作用.但是,如果用户在收到数据之前在 之前关闭片段(按回去),它将崩溃:

It works if the fragment is still shown when data is received. But if user close the fragment (pressing back) before data is received, it crashes:

java.lang.IllegalStateException: my_text_view must not be null

如何避免这种情况?

我当然可以使用my_text_view?.text = ...,但是

  • 总有一天我会忘记放?

无法解决片段被销毁后侦听器仍然存活的问题

It doesn't solve the problem that the listener stays alive after the fragment is destroyed

我想我想要类似

I think I want something like addOnSuccessListener(Activity, OnSuccessListener) but for Fragment instead Activity

推荐答案

您可以在回调中检入是否仍将该片段添加到其主机活动中,

You can check in your callback if the fragment is still added to its host activity,

FirebaseFirestore.getInstance()
.collection("users")
.document("1")
.get()
.addOnSuccessListener { doc ->
    if (isAdded) {
        my_text_view.text = doc["name"] as String
    }
}

但是,更好的解决方案是将业务逻辑移至视图模型.

However, a better solution would be to move your business logic to a viewmodel.

这篇关于Kotlin视图绑定java.lang.IllegalStateException:侦听器内的视图不能为null的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆