2

I am using Firebase Recycler Adapter on the Real Time Data Base (RTDB). Unfortunately, the query feature for the RTDB is quite limited and is causing me some problems. Here is the problem I am trying to solve:

Imagine I have an object model consisting of the name and the national origin of a person. I can query all the people with a particular national origin as shown below:

        Query query = FirebaseDatabase.getInstance().getReference().child("People").orderByChild("nationalOrigin").equalTo("USA");
    FirebaseRecyclerOptions<People> options = new FirebaseRecyclerOptions.Builder<People>()
            .setQuery(query, People.class)
            .build();

This correctly query all the people with national origin being "USA". However, what if I also want to sort the data alphabetically based on the name of the person before populating the recycle view. What is the best way of dong this?

Thanks in advance.

LeaningAndroid
  • 445
  • 2
  • 4
  • 12
  • 1
    I have run into the same issue before but never figured out a way around it. Firebase Firestore is now providing much stronger queries. You may consider switching to Firestore. – MrAliB Jan 25 '20 at 22:39
  • Thank you. I have considered moving to firebase and may still do it. But at this time, I prefer to stay with RTDB. Thank you for the suggestion though. – LeaningAndroid Jan 25 '20 at 22:54
  • 1
    Realtime Database can't sort or filter on multiple fields. You will either need to make a composite field, or sort the data on the client, and use a custom adapter to display in a recyclerview. – Doug Stevenson Jan 25 '20 at 23:31
  • 1
    In your case you could add a property `"nationalOrigin_name": "USA_LeaningAndroid"` and order/filter on that with something like: `ref.orderByChild("nationalOrigin_name").startAt("USA_").endAt("USA~")`. With this you'd get all child nodes from USA, in the order of their name. For a longer example, see my answer to https://stackoverflow.com/questions/26700924/query-based-on-multiple-where-clauses-in-firebase – Frank van Puffelen Jan 25 '20 at 23:41

0 Answers0