Firestore - 为什么检查DocumentSnapshot是否为空并且调用是否存在?

Flo*_*her 1 java android firebase google-cloud-firestore

Firestore文档中查看此代码示例:

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());
        }
    }
});
Run Code Online (Sandbox Code Playgroud)

https://firebase.google.com/docs/firestore/query-data/get-data

为什么检查一下document != null?如果我正确读取源代码(初学者),该exists方法将在内部检查无效.

Fra*_*len 9

一个成功完成任务,绝不会通过nullDocumentSnapshot.如果请求的文档不存在,您将获得一个空快照.这意味着:

  • 调用document.exists()返回false
  • 调用document.getData()抛出异常

所以document != null在打电话之前确实没有理由检查document.exists().

  • 谢谢。很高兴看到我的结论是正确的,因为我是一个初学者。 (2认同)