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.
Advertisement
Answer
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:
- Calling
document.exists()returns false - Calling
document.getData()throws an exception
So there is indeed no reason to check if document != null before calling document.exists().