Skip to content Skip to sidebar Skip to footer

How To Sort Firebase Records By Two Fields (android)

I'm using FirebaseRecyclerAdapter and pass FirebaseRecyclerOptions with some query into constructor. Each item has number of fields including timestamp a and another integer field

Solution 1:

Unfortunately, Firebase Realtime database does not support queries on multiple properties, supports only queries on a single child property. So, you're correct in guessing that you'll need to create an extra field to keep both fields. So to achieve this, you need to create a new field which in your database should look like this:

Firebase-root
   |
   --- itemId
          |
          --- a: valueOfA
          |
          --- b: valueOfB
          |
          --- a_b: valueOfA_valueOfB

So as you see, the a_b property combines the values that you want to filter on.

Unlike Firebase Realtime database, Cloud Firestore allows compound queries. You should take a look at this. So a query as the one below is allowed in Cloud Firestore without creating a combined property.

itemIdRef.whereEqualTo("a", "valueOfA").whereEqualTo("b", "valueOfB");

When you order strings this is the normal ordering method. A quick fix would be to add two zeros before each second element like this: "1516428687_001", "1516428687_002", "1516428687_012". Now your order will be fine. For more explanations, please see my answer from this post.

Post a Comment for "How To Sort Firebase Records By Two Fields (android)"