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:
Query query= firestoredb.collection('items').document(docid).orderby('price').orderby('itemcategory').orderby('name');
Is not possible in Cloud Firestore because firestoredb.collection('items').document(docid) return a DocumentReference object and you cannot call orderBy() method on it. So assuming you want to use a query, the following line of code:
Query query= firestoredb.collection('items').orderby('price').orderby('itemcategory').orderby('name');
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 or Direction.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:
Query query;
switch (option) {
case "price":
query = firestoredb.collection('items').orderby('price');
break;
case "itemcategory":
query = firestoredb.collection('items').orderby('itemcategory');
break;
case "price_itemcategory":
query = firestoredb.collection('items').orderby('price').orderby('itemcategory');
break;
case "name":
query = firestoredb.collection('items').orderby('name');
break;
case "price_name":
query = firestoredb.collection('items').orderby('price').orderby('name');
break;
default:
query = firestoredb.collection('items'); //No ordering
break;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With