Issue
I'm new to Firebase usage with Android development and I've been stuck on this issue. Everything is working fine and I'm able to successfully display users i a RecyclerView with FirebaseRecyclerAdapter, but here's my issue, I only want to display users whom their requestStatus is set to "true", not all the users. Tried searching for this to no avail.
This is my Firebase realtime database.
Calling the database in onCreateView and setting the adapter
val database = FirebaseDatabase.getInstance().getReference().child("users")
val clientsRecycler = binding.clientsRecycler
val options: FirebaseRecyclerOptions<User> = FirebaseRecyclerOptions.Builder<User>()
.setQuery(database, User::class.java)
.build()
adapter = Adapter(options)
clientsRecycler.adapter = adapter
My adapter class
class Adapter(options: FirebaseRecyclerOptions<User>) :
FirebaseRecyclerAdapter<User, Adapter.ClientsViewHolder>(options) {
class ClientsViewHolder(private val binding: ClientItemBinding) : RecyclerView.ViewHolder(binding.root) {
val name = binding.clientName
val phone = binding.clientPhone
val location = binding.clientLocation
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ClientsViewHolder {
return ClientsViewHolder(ClientItemBinding
.inflate(LayoutInflater.from(parent.context), parent, false))
}
override fun onBindViewHolder(holder: ClientsViewHolder, position: Int, model: User) {
holder.name.text = model.name
holder.phone.text = model.phone
holder.location.text = model.location
}}
How can I only display John (whom's requestStatus is set to true) and not Robert?
I'm guessing the solution has got to do with FirebaseDatabase.getInstance().getReference().child("users") but I'm just not sure how can I tell Firebase that I only want users with "true" requestStatus
Solution
Found the solution.
Change
val database = FirebaseDatabase.getInstance().getReference().child("users")
to
var filterQuery = FirebaseDatabase.getInstance().getReference().child("users").orderByChild("requestStatus").equalTo("true")
and
val options: FirebaseRecyclerOptions<User> = FirebaseRecyclerOptions.Builder<User>()
.setQuery(database, User::class.java)
.build()
to
val options: FirebaseRecyclerOptions<User> = FirebaseRecyclerOptions.Builder<User>()
.setQuery(filterQuery, User::class.java)
.build()
Basically instead of using a DatabaseReference just create a query and then pass it to setQuery()
Answered By - M.Ed
Answer Checked By - Robin (JavaFixing Admin)