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
wheregetItemCount()
return 0. - Or I can use
FirestoreRecyclerOptions.Builder#setSnapshotArray
(instead ofsetQuery
) 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.