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();
}
}
}
}
});
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With