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 ,这意味着您的tasknull并且将打印出以下消息:

 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。

如果documentSnapshotnullable ,则应执行以下操作:

 if (documentSnapshot != null) { if (documentSnapshot.exists()) { //exists } else { //doesn't exist } }