0

What would be the most efficient way to check for a value of a field in Firestore collection? Suppose there are multiple documents in organizations table, I want to loop through every 'orgcode' field in documents, and see if at least 1 matches.

image

public static boolean isCodeValidationSuccessful(String _code){

    Log.i(TAG, "code validation reached");

    mDb = FirebaseFirestore.getInstance();

    mDb.collection("organizations")
            .whereEqualTo("orgcode", _code).get()
            .addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
                @Override
                public void onComplete(@NonNull Task<QuerySnapshot> task) {
                    if(!task.isSuccessful()) {
                        mIsSuccessful = true;
                        Log.i(TAG, "passcode successful, task: " + task.getResult());
                    }
                    else{
                        mIsSuccessful = false;
                    }
                }
            });
    return mIsSuccessful;
}
Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
Sean LEE
  • 23
  • 4
  • Please only use the `android-studio` tag for questions about the Android Studio IDE itself. For questions about Android programming in general, use the `android` tag. This also then immediately enables syntax highlighting code blocks in your question, so it's a win:win. – Frank van Puffelen Jan 19 '22 at 19:14
  • I may be missing something, but in order to check if any documents have a matching field you would need to do `.where("orgcode", "==", "myvalue")` like your code is already doing. You could also limit the results to 1. Then you can simply check the size property on the snapshot return. – Tristan Jan 19 '22 at 19:15
  • The query you have looks fine to me, although I'd typically [limit to a single result](https://firebase.google.com/docs/firestore/query-data/order-limit-data#order_and_limit_data) if you're only looking to see whether any document exists matching the condition. – Frank van Puffelen Jan 19 '22 at 19:16
  • Aha, I see the problem now: data is loaded from Firestore (and most modern cloud APIs) asynchronously. By the time your `return mIsSuccessful` the data hasn't loaded yet and the code in `onComplete` hasn't executed. See the questions I linked for more on this. – Frank van Puffelen Jan 19 '22 at 19:17
  • @FrankvanPuffelen Thank you for your replies :) seems like changing it to onSuccess can solve the problem? – Sean LEE Jan 19 '22 at 19:25

0 Answers0