Reputation: 5876
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
Upvotes: 4
Views: 3098
Reputation: 29320
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.
Upvotes: 2