7

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();
                    }
                }
            }
        }
    });
André Kool
  • 4,880
  • 12
  • 34
  • 44
Sami Nazari
  • 175
  • 3
  • 10

4 Answers4

4

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.

Alex Mamo
  • 130,605
  • 17
  • 163
  • 193
  • Tried this, only works when data exists, and if the data doesn't exists, it returns nothing, even when I added else statement or ( !document.exists() ) it didn't work! – Sami Nazari May 31 '18 at 07:49
  • If it only works when data exists, it means that you are not looking for the data that does not exist. So it is normal that the second part of the if statement is not called. But this is the only way in which you can very if the data exists in a query snapshot. – Alex Mamo May 31 '18 at 08:02
  • Please also see the comment that I have added to the second Toast in my updated answer. – Alex Mamo May 31 '18 at 08:06
  • I updated the question (code part) I commented the section that isn't runninig even if there is no data! – Sami Nazari May 31 '18 at 08:28
  • logically that part must run when there is no data, but its not running! – Sami Nazari May 31 '18 at 08:35
  • This is because your `task.isSuccessful()` returns `false` and your if statement isn't triggered at all. Please add the `else` part also for the first if statement. What is happening now? – Alex Mamo May 31 '18 at 08:36
  • added else part for the first if statement, still when there is no data its not working! – Sami Nazari May 31 '18 at 09:44
  • The result of this `Task` is a `DocumentSnapshot`. Whether or not the underlying document actually exists is available via the `exists` method. If the document does exist you can call `getData` to get at the contents of it, as seen [here](https://stackoverflow.com/questions/46574380/check-if-user-exists-in-firestore). As i suppose you are checking on wrong reference. I cannot think at anything else. – Alex Mamo May 31 '18 at 10:10
  • it returns data when there is data in the reference, and runs the if statement and its toast message, but nothing happens when there is no data returned. Anyways, thank you! – Sami Nazari May 31 '18 at 10:19
  • You're welcome but I think you didn't fully understood. Please see this [post](https://stackoverflow.com/questions/49705216/firestore-why-check-if-documentsnapshot-is-not-null-and-call-exists) for a better understanding. – Alex Mamo May 31 '18 at 10:24
  • my problem is not with understanding this "Task" thing, I know how it works, my problem is that when data does not exists it never runs the part that logically it must run. your answers, it didn't solve my problem. still I haven't found any solution, I have only 6 reputations and I can't start chat! – Sami Nazari May 31 '18 at 10:37
1

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

na_christ
  • 23
  • 5
0

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
}
stackUser
  • 13
  • 4
0

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();
        }
    }

}
});
fsdklfm
  • 17
  • 6