Firestore addSnapshotListener With Activity (IllegalStateException: FragmentManager is already executing transactions)

May 17, 2019

I was using Query.addSnapshotListener in a Fragment

class TestFragment : Fragment() {    override fun onActivityCreated(savedInstanceState: Bundle?) {        val query = ...        query.addSnapshotListener(activity!!) { querySnapshot, e ->        }    }}

and bump into the following exception

java.lang.IllegalStateException: FragmentManager is already executing transactions        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2315)

The error doesn't happend instantly. If I launch the App, pressed back (app goes into background) and launch the app again, the error will occur. Similar incidents have been reported.

NOTE: I am using com.google.firebase:firebase-firestore:19.0.0.

Solution 1: ListenerRegistration

class TestFragment : Fragment() {    private var queryRegistration: ListenerRegistration? = null    override fun onActivityCreated(savedInstanceState: Bundle?) {        val query = ...        queryRegistration = query.addSnapshotListener { querySnapshot, e ->        }    }    override fun onDestroy() {        super.onDestroy()        queryRegistration?.also {            it.remove()            collectionRegistration = null        }    }}

Solution 2: addSnapshotListener with LifecycleOwner

Use code from Firestore addSnapshotListener with LifecycleOwner.

// this = LifecyclerOwnerquery.addSnapshotListener(this) { documentSnapshot, e ->}

Solution 3: QuerySnapshotLiveData

Use code from Android Firestore Query addSnapshotListener as LiveData.

// this = LifecyclerOwnerquery.asSnapshotLiveData().observe(this, Observer { result ->    if (result.isSuccessful) {        // do something        val query = result.data()    }    else {        Timber.e(result.error())    }})

❤️ Is this article helpful?

Buy me a coffee ☕ or support my work via PayPal to keep this space 🖖 and ad-free.

Do send some 💖 to @d_luaz or share this article.

✨ By Desmond Lua

A dream boy who enjoys making apps, travelling and making youtube videos. Follow me on @d_luaz

👶 Apps I built

Travelopy - discover travel places in Malaysia, Singapore, Taiwan, Japan.