Pavel
Pavel

Reputation: 5876

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

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

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

Upvotes: 4

Views: 3098

Answers (1)

Francesc
Francesc

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

Related Questions