Search code examples
javaandroidfirebasefirebase-realtime-databasefirebaseui

Querying a FirebaseListAdapter to only return specific children to a custom view


I have an Android application connecting to Firebase, I'm using a FirebaseListAdapter to populate a custom layout with data from my DB reference.

This is working as expected. But is it possible to query this data to only return certain entry's?

For example if this were a sample of my data:

"students" : {  
  "-KTA7xijNrK1SK98rZns" : {     
    "name" : "Ro",      
    "age" : 28,         
    "email" : "test@test.com"
  },

"-KTABiJuH2-RXwmp0Rcu" : {   
   "name" : "Tom",      
   "age" : 22,         
   "email" : "test1@test.com"
  }...

So currently all students are being populated into the ListAdapter via the custom view which is what I want for the initial load, but based on a button click if I wanted to only show students over a certain age or students with a certain name is it possible to somehow integrate these query into the FirebaseListadapter?

Current List adapter code.

 //Firebase DB srefrence
    mDatabaseStolen =    FirebaseDatabase.getInstance().getReference().child("students");

FirebaseListAdapter<Student> bikeAdapter = new FirebaseListAdapter<Studnet>
            (getActivity(), Student.class, R.layout.list_item, mDatabase) {
        @Override
        protected void populateView(View v, Student model, int position) {


                // Find the TextView IDs of list_item.xml
                TextView nameView = (TextView) v.findViewById(R.id.name);
                TextView ageView = (TextView) v.findViewById(R.id.age);
                TextView emailView = (TextView) v.findViewById(R.id.email);

                //setting the textViews to Student data
                nameView.setText(model.getname());
                ageView.setText(String.valueOf(model.getAge()));
                emailView.setText(model.getEmail());
  }
 };

Any help appreciated.


Solution

  • You can construct a FirebaseListAdapter based on a DatabaseReference or based on a Query. with a DatabaseReference it will show all the data at a location. But when you use a Query you can show a subset of the data at the location.

    Say that you want to show only students between ages 20 and 25:

    students =    FirebaseDatabase.getInstance().getReference().child("students");
    studentsQuery = students.orderByChild("age").startAt(20).endAt(25);
    
    bikeAdapter = new FirebaseListAdapter<Student>
         (getActivity(), Student.class, R.layout.list_item, studentsQuery) {
    

    Also see the Firebase documentation on queries.