I’m using Firebase Database to show data in RecyclerView. Now I want to add a filter option by using an Android spinner. When I try to use different queries code doesn’t work. How can I use the spinner to show data for only 1 query and refresh this by changing the spinner item? This code now works without a spinner click item.
DatabaseReference reference = FirebaseDatabase.getInstance().getReference(); query = reference.child("student"); FirebaseRecyclerOptions<ModelPromocje> options = new FirebaseRecyclerOptions.Builder<ModelPromocje>() .setQuery(query, ModelPromocje.class) .build();
Spinner click item, when the position is 0 it should show all data
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { @Override public void onItemSelected(AdapterView<?> parent, View view, int position, long id) { if (position == 0){ query = reference.child("student"); } else if (position == 1){ query = reference.child("student").orderByChild("course").equalTo("Math"); } } @Override public void onNothingSelected(AdapterView<?> parent) { } });
Advertisement
Answer
When the user selects an option in the spinner, after you create the new query
for the selected option, you’ll need to update the adapter to use that new query.
You do that by creating a new FirebaseRecyclerOptions
object with the new query, and then set that on the adapter by calling its updateOptions
.
So something like this in your onItemSelected
:
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) { if (position == 0){ query = reference.child("student"); } else if (position == 1){ query = reference.child("student").orderByChild("course").equalTo("Math"); } new FirebaseRecyclerOptions.Builder<ModelPromocje>() .setQuery(query, ModelPromocje.class) .build(); // Change options of adapter. mAdapter.updateOptions(newOptions) }
There mAdapter
is whatever the FirebaseRecyclerAdapter
is that you originally also passed your options to.