I am making a chat app on Android that uses google firebase to store messages that users write to each other. To display these messages to the users I read them from the dat
In addition to what's been said in Peter's answer, according to FirebaseRecyclerAdapater latest api documentation, you can create a FirebaseRecyclerAdapter
passing in a FirebaseRecyclerOptions
instance which is created by a builder. In the builder you specify a lifecycle owner so you don't have to modify either its onStart
or its onStop
manually:
private fun MainActivity.setUpFirebaseRecyclerAdapter():
FirebaseRecyclerAdapter {
val options = FirebaseRecyclerOptions.Builder()
.setQuery(ONLINE_USERS.limitToLast(10), User::class.java)
.setLifecycleOwner(this)
.build()
return object : FirebaseRecyclerAdapter(options){
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ListOnlineViewHolder {
return ListOnlineViewHolder(
LayoutInflater.from(parent.context)
.inflate(R.layout.user_layout, parent, false))
}
override fun onBindViewHolder(holder: ListOnlineViewHolder, position: Int, model: User) {
holder.bindMessage(model)
}
}
}
The options builder is made up of a setQuery method which takes in a reference to the db and a model object; the setLifecycleOwner which takes in the activity that will trigger the adapter updates.