Sami Nazari
Sami Nazari

Reputation: 175

how to know if data exists in a firestore query snapshot?

This is my code where I want to get data and to know if data exists or not. Problem is that if data exists it runs { if(task.isSuccessful() } but if data doesn't exists, it does nothing!

How can I know that data doesn't exist? I added other { else } statements but it didn't work.

CollectionReference reference = firestore.collection("Carts").document(FirebaseAuth.getInstance().getCurrentUser().getUid())
            .collection("Carts");
    reference.whereEqualTo("ordered",false).get().addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
        @Override
        public void onComplete(@NonNull Task<QuerySnapshot> task) {
            if (task.isSuccessful()) {
                for (QueryDocumentSnapshot document : task.getResult()) {
                    if(document.exists()){
                        Toast.makeText(ListProducts.this, "Exists", Toast.LENGTH_SHORT).show();
                    }
                    else {
                        // This part is not running even if there is no data
                        Toast.makeText(ListProducts.this, "NOPE", Toast.LENGTH_SHORT).show();
                    }
                }
            }
        }
    });

Upvotes: 7

Views: 9348

Answers (4)

na_christ
na_christ

Reputation: 23

you need to verify if documents list is empty or not

FirebaseFirestore.getInstance().collection(collectionName).whereEqualTo(cle
            , valeur)
            .get()
            .addOnCompleteListener(task -> {
                if (task.isSuccessful()) {
                    QuerySnapshot querySnapshot = task.getResult();
                        if (querySnapshot.isEmpty()) { // no documents found
                            // Type your code yere
                        } else {
                            for (QueryDocumentSnapshot document : querySnapshot){

                            }
                        }
                } else {
                    Log.d(TAG, methodName + task.getException());
                }
            });

if i execute

for (int i = 2; i < 1; i ++) { }

that's okay but we will never get into this loop. It's the same for the above code

Upvotes: 1

fsdklfm
fsdklfm

Reputation: 17

I know I'm a little bit late and don't know if you found your answer. But I just found out how to do it:

reference.whereEqualTo("ordered",false).get().addOnSuccessListener(new OnSuccessListener<QuerySnapshot>() {
@Override
public void onSuccess(QuerySnapshot queryDocumentSnapshots) {

    if (queryDocumentSnapshots.isEmpty()) {
        Snackbar.make(mainContactsLayout, "No matches found", Snackbar.LENGTH_SHORT).show();
    } else {

        for (DocumentSnapshot documentSnapshot : queryDocumentSnapshots.getDocuments()) {
            Snackbar.make(mainContactsLayout, documentSnapshot.getId(), Snackbar.LENGTH_SHORT).show();
        }
    }

}
});

Upvotes: 0

stackUser
stackUser

Reputation: 13

Check the existence of document when the task is completed successfully by isEmpty() or size() methods

if (task.isSuccessful()) {
    if(task.getResult().isEmpty()){
        //There is no such document do what ever you want!   
    }
    else {
        for (QueryDocumentSnapshot document : task.getResult()) {
            if (document.exists()) {
                Toast.makeText(ListProducts.this, document.toString(), Toast.LENGTH_SHORT).show();
            }
        }
    }
}

or

if(task.getResult().size > 0){
    //Document exist
}

Upvotes: 0

Alex Mamo
Alex Mamo

Reputation: 138824

You need to use exists() method directly on the QueryDocumentSnapshot object like this:

CollectionReference reference = firestore.collection("Carts").document(FirebaseAuth.getInstance().getCurrentUser().getUid())
            .collection("Carts");
    reference.whereEqualTo("ordered",false).get().addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
        @Override
        public void onComplete(@NonNull Task<QuerySnapshot> task) {
            if (task.isSuccessful()) {
                for (QueryDocumentSnapshot document : task.getResult()) {
                    if (document.exists()) {
                         Toast.makeText(ListProducts.this, document.toString(), Toast.LENGTH_SHORT).show();
                    }
                }
            } else{
                //This Toast will be displayed only when you'll have an error while getting documents.
                Toast.makeText(ListProducts.this, task.getException().toString(), Toast.LENGTH_SHORT).show();
            }
        }
    });

task.isSuccessful() is used to to handle success or failure in your listener while exists() method when called on an object of QueryDocumentSnapshot class which extends DocumentSnapshot class returns:

true if the document existed in this snapshot.

Upvotes: 4

Related Questions