gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 09:46:54 24 4
gpt4 key购买 nike

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

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

为什么要检查 document != null?如果我正确阅读了源代码(初学者),exists 方法会在内部检查无效性。

最佳答案

成功完成的任务永远不会为 DocumentSnapshot 传递 null。如果请求的文档不存在,您将得到一个空的快照。这意味着:

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

因此确实没有理由在调用 document.exists() 之前检查是否 document != null

关于java - Firestore - 为什么要检查 DocumentSnapshot 是否不为空并且调用是否存在?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49705216/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com