How to implement multiple order by in android fire

2019-07-26 01:22发布

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.

2条回答
Explosion°爆炸
2楼-- · 2019-07-26 02:01

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;
查看更多
别忘想泡老子
3楼-- · 2019-07-26 02:05
 Query query=firestoredb.collection("items"); 
 if(PRICE.equals("price")) {
      query = query.orderby('price'); 
 }
 if(NAME.equals("name")) {
      query = query.orderby('name'); 
 }
 if("itemCategory"){
      query = query.orderby('itemCategory');
 }
查看更多
登录 后发表回答