Why use FirestoreRecyclerAdapter?
- Automatically update snapshot changes (ADDED, CHANGED, REMOVED, MOVED) to
RecyclerView
- Lifecyclew aware through
FirestoreRecyclerOptions.Builder#setLifecycleOwner
- Support for paging with
FirestorePagingAdapter
Dependencies
dependencies {
// https://mvnrepository.com/artifact/com.firebaseui/firebase-ui-firestore
implementation 'com.firebaseui:firebase-ui-firestore:4.3.1'
}
Setup
val query = ...val builder = FirestoreRecyclerOptions.Builder<Quote>() .setQuery(query, object : SnapshotParser<Quote> { override fun parseSnapshot(snapshot: DocumentSnapshot): Quote { return snapshot.toObject(Quote::class.java)!!.also { it.id = snapshot.id } } }) .setLifecycleOwner(this)val adapter = FirestoreQuoteAdapter(options)recyclerView.adapter = adapter
Model
class Quote( @get:Exclude override var id : String? = null, @JvmField @PropertyName(CONTENT) var content: String? = "", @JvmField @PropertyName(SOURCE) var source: String? = null) { companion object { const val COLLECTION_NAME = "quote" const val CONTENT = "content" const val SOURCE = "source" }}
Adapter
class FirestoreQuoteAdapter(options: FirestoreRecyclerOptions<Quote>) : FirestoreRecyclerAdapter<Quote, FirestoreQuoteAdapter.ViewHolder>(options) { override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder { val view = LayoutInflater.from(parent.context) .inflate(R.layout.quotelist_item, parent, false) return ViewHolder(view) } override fun onBindViewHolder(holder: ViewHolder, position: Int, item: Quote) { // val id = snapshots.getSnapshot(position).id holder.apply { contentTextView.text = item.content sourceTextView.text = item.source } } inner class ViewHolder(override val containerView: View) : RecyclerView.ViewHolder(containerView), LayoutContainer}