Kotlin View Binding java.lang.IllegalStateException: view must not be null inside listener

心已入冬 提交于 2019-12-06 11:14:17

问题


I'm using View Binding from Kotlin Android Extensions:

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

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

How do I avoid this?


Of course I can use my_text_view?.text = ... but

  • Someday I can forget to put ?

  • 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


回答1:


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.



来源:https://stackoverflow.com/questions/53510119/kotlin-view-binding-java-lang-illegalstateexception-view-must-not-be-null-insid

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!