在Firestore query-data get-data文档中,我想知道document != null
将在什么情况下评估为假?不应该是!document.exists()
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) {
Log.d(TAG, "DocumentSnapshot data: " + task.getResult().getData());
} else {
Log.d(TAG, "No such document");
}
} else {
Log.d(TAG, "get failed with ", task.getException());
}
}
});
onComplete()
回调提供了Task的Google Task<DocumentSnapshot>
实例,并且在此调用getResult()
应返回DocumentSnapshot
,而不是null
。
这引起了我的兴趣,所以我做了一些测试:我将OnCompleteListener
附加到我知道不存在的文档中:
FirebaseFirestore.getInstance()
.collection("this-does-not-exist")
.document("neither-does-this")
.get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
@Override
public void onComplete(@NonNull Task<DocumentSnapshot> task) {
if (task.isSuccessful()) {
if (task.getResult() == null) Log.d(TAG, "getResult is null");
Log.d(TAG, "getResult: " + task.getResult());
}
}
});
执行时,task.getResult() == null
检查计算为false
,因此消息“getResult为null”不会写入日志。
但是,从toString()
返回时调用getResult()
会引发以下错误:
java.lang.IllegalStateException: This document doesn't exist. Use DocumentSnapshot.exists() to check whether the document exists before accessing its fields.
这明确规定使用exists()
而不是null检查,但documentation for "get a document"说:
注意:如果docRef引用的位置没有文档,则生成的文档将为null。
此外,同一文档页面上的其他语言示例都使用exists()
,但Android和Objective-C除外。最重要的是:Java示例使用exists()
:
DocumentReference docRef = db.collection("cities").document("SF"); // asynchronously retrieve the document ApiFuture<DocumentSnapshot> future = docRef.get(); // ... // future.get() blocks on response DocumentSnapshot document = future.get(); if (document.exists()) { System.out.println("Document data: " + document.getData()); } else { System.out.println("No such document!"); }
在这种情况下,我打赌这似乎是文档中的一个错误,我们应该使用document.exists()
而不是document != null
。