Take a look at this code example from the Firestore
documentation:
DocumentReference docRef = db.collection("cities").document("SF");
docRef.get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
@Override
public void onComplete(@NonNull Task<DocumentSnapshot> task) {
if (task.isSuccessful()) {
DocumentSnapshot document = task.getResult();
if (document != null && document.exists()) {
Log.d(TAG, "DocumentSnapshot data: " + document.getData());
} else {
Log.d(TAG, "No such document");
}
} else {
Log.d(TAG, "get failed with ", task.getException());
}
}
});
https://firebase.google.com/docs/firestore/query-data/get-data
Why check if document != null
? If I read the source code correctly (beginner), the exists
method checks for nullity internally.
A successfully completed task will never pass null
for the DocumentSnapshot
. If the requested document does not exist, you'll get an empty snapshot. This means that:
document.exists()
returns falsedocument.getData()
throws an exceptionSo there is indeed no reason to check if document != null
before calling document.exists()
.
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