How to implement multiple order by in Android Firestore
based on different if conditions?
I want to sort my firestore items based on different fieldvalues like this:
Query query= firestoredb.collection('items').document(docid).orderby('price').orderby('itemcategory').orderby('name**');
But how many orderby
will be added is dynamic . It will decide during runtime i.e what user will select from sort options.
So how would I make my Firestore
query in android?
Please help me.
A query like the one you are using in your code:
Is not possible in Cloud Firestore because
firestoredb.collection('items').document(docid)
return a DocumentReference object and you cannot callorderBy()
method on it. So assuming you want to use a query, the following line of code:Will work perfectly fine. There is no problem in Firestore to order by multiple fields. You can even set the direction passing as the second argument:
Direction.ASCENDING
orDirection.DESCENDING
.Edit:
According to your comment, you should create an if statement or even better, a switch statement and accordingly to what the user is seleting to create a new query object. So if the user selects only price, then the query should look like this:
firestoredb.collection('items').orderby('price')
, that's it. See an example below: