Reputation: 155
I have Constructed a firebase query like this for all my dropdown spinners in app.
Actually i have more than 20 spinners in my android app to search users from firebase firestore collection based on any dropdown selected. currently i handled all possible scenario by using if else condition and make compound query base on any selected spinner. but this is not a good approach which i am currently using. i need to append query next to any query without handle any spinner check..her is my code.
Query query;
CollectionReference collection =
firestore.collection(Constants.MEMBERS);
query = collection;
if (rangeBarRating.getRightIndex() != 0 && spinnerReligion.getSelectedItemPosition() != 0){
query = collection.whereEqualTo(Constants.RELIGION,spinnerReligion.getSelectedItem()).whereEqualTo(Constants.REGISTERATION_STATUS,rangeBarRating.getRightIndex());
} else if (spinnerCountry.getSelectedItemPosition() != 0){
query = collection.whereEqualTo(Constants.COUNTRY_LIVING_IN,spinnerCountry.getSelectedItem());
}else if (rangeBarRating.getRightIndex() != 0){
query = collection.whereEqualTo(Constants.REGISTERATION_STATUS,rangeBarRating.getRightIndex());
}else if ((rangeBarAge.getLeftIndex()+18) > 18){
query = collection.whereGreaterThanOrEqualTo(Constants.AGE,(rangeBarAge.getLeftIndex()+18));
}
I need dynamically approach like i only use if statement not if else . if some spinner is selected then append that spinner value in my query and get desired result.
Upvotes: 0
Views: 500
Reputation: 599541
You have a small mistake in how you assign the conditional query. You want each condition to be added to the existing query, but are in fact constantly rebuilding a new query from the collection. To fix this, build from query
every time you add a condition:
firestore.collection(Constants.MEMBERS);
query = collection;
if (rangeBarRating.getRightIndex() != 0 && spinnerReligion.getSelectedItemPosition() != 0){
query = query.whereEqualTo(Constants.RELIGION,spinnerReligion.getSelectedItem()).whereEqualTo(Constants.REGISTERATION_STATUS,rangeBarRating.getRightIndex());
} else if (spinnerCountry.getSelectedItemPosition() != 0){
query = query.whereEqualTo(Constants.COUNTRY_LIVING_IN,spinnerCountry.getSelectedItem());
}else if (rangeBarRating.getRightIndex() != 0){
query = query.whereEqualTo(Constants.REGISTERATION_STATUS,rangeBarRating.getRightIndex());
}else if ((rangeBarAge.getLeftIndex()+18) > 18){
query = query.whereGreaterThanOrEqualTo(Constants.AGE,(rangeBarAge.getLeftIndex()+18));
}
Upvotes: 1