Android Load FirestoreUI FirestoreRecyclerAdapter With Empty Query (Clear RecyclerView)

EmptySnapshotArray

I am using FirestoreRecyclerAdapter to load firestore query into RecyclerView.

Why need empty query/empty recycler view?

I already loaded RecyclerView with Query data when user signin, then I need to empty/clear the RecyclerView when user signout.

  • I could hide the RecyclerView
  • Or create a Firestore Query which I am sure will not return any result.
  • Or I can create a blank RecyclerView.Adapter where getItemCount() return 0.
  • Or I can use FirestoreRecyclerOptions.Builder#setSnapshotArray (instead of setQuery) and assign an empty snapshot array.

EmptySnapshotArray

import com.firebase.ui.firestore.ObservableSnapshotArrayimport com.firebase.ui.firestore.SnapshotParserimport com.google.firebase.firestore.DocumentSnapshotclass EmptySnapshotArray<T>: ObservableSnapshotArray<T>(SnapshotParser<T> {    TODO()}) {    // class EmptyArray<T>(parser: SnapshotParser<T>): ObservableSnapshotArray<T>(parser) {    override fun getSnapshots(): MutableList<DocumentSnapshot> {        return mutableListOf()    }}
class MyActivity:  AppCompatActivity() {    private lateinit var adapter: LocalAdapter    private fun createAdapter(): LocalAdapter {        if (::adapter.isInitialized) {            // call this before replacing the adapter to prevent invalid snapshot            adapter.stopListening()            lifecycle.removeObserver(adapter)        }        // query=null when user not signin        val query = ...        // Quote is Model        val builder = FirestoreRecyclerOptions.Builder<Quote>()            .setLifecycleOwner(this)        if (query != null) {            builder.setQuery(query, object : SnapshotParser<Quote> {                override fun parseSnapshot(snapshot: DocumentSnapshot): Quote {                    return Quote.toObject(snapshot)!!.also {                        it.id = snapshot.id                    }                }            })        }        else {            // no query, set empty            builder.setSnapshotArray(EmptySnapshotArray())        }        val options = builder.build()        return FirestoreQuoteAdapter(options, viewModel).also {            adapter = it        }    }    private fun initUi() {        recyclerView.adapter = createAdapter()    }}

NOTE: Refer to Android Firestore RecyclerView With FirestoreUI FirestoreRecyclerAdapter for Quote and FirestoreQuoteAdapter implementation.

❤️ 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.