Firestore – 为什么检查DocumentSnapshot是否为空并且调用是否存在?
看一下Firestore
文档中的这个代码示例:
DocumentReference docRef = db.collection("cities").document("SF"); docRef.get().addOnCompleteListener(new OnCompleteListener() { @Override public void onComplete(@NonNull Task 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
方法在内部检查null。
成功完成的任务永远不会为DocumentSnapshot
传递null
。 如果请求的文档不存在,您将获得一个空快照。 这意味着:
- 调用
document.exists()
返回false - 调用
document.getData()
会抛出exception
因此,在调用document.exists()
之前,确实没有理由检查document != null
。
如果执行以下语句:
document != null
它将被评估为false
,这意味着您的task
为null
并且将打印出以下消息:
Log.d(TAG, "No such document");
但是,如果要在task
对象上调用方法(例如toString()),则会抛出以下错误:
java.lang.IllegalStateException: This document doesn't exist. Use DocumentSnapshot.exists() to check whether the document exists before accessing its fields.
此消息明确告诉您使用exists()方法而不是检查null。
关于如何获取文档方法的官方文档说:
注意:如果docRef引用的位置没有文档,则生成的文档将为null。
如果documentSnapshot
为nullable
,则应执行以下操作:
if (documentSnapshot != null) { if (documentSnapshot.exists()) { //exists } else { //doesn't exist } }