Firestore - 为什么检查DocumentSnapshot是否为空并且调用是否存在? [英] Firestore - Why check if DocumentSnapshot is not null AND call exists?

查看:207
本文介绍了Firestore - 为什么检查DocumentSnapshot是否为空并且调用是否存在?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Take a look at this code example from the Firestore documentation:

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 ?如果我正确读取源代码(初学者),存在方法在内部检查无效。

Why check if document != null? If I read the source code correctly (beginner), the exists method checks for nullity internally.

推荐答案

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

A successfully completed task will never pass null for the DocumentSnapshot. If the requested document does not exist, you'll get an empty snapshot. This means that:


  • 调用 document.exists()返回false

  • 调用 document.getData()抛出异常

  • Calling document.exists() returns false
  • Calling document.getData() throws an exception

所以在调用 document.exists()之前,确实没有理由检查 document!= null

So there is indeed no reason to check if document != null before calling document.exists().

这篇关于Firestore - 为什么检查DocumentSnapshot是否为空并且调用是否存在?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆