【问题标题】:Attempt to invoke virtual method 'boolean com.google.firebase.firestore.DocumentSnapshot.exists()' on a null object reference尝试在空对象引用上调用虚拟方法“boolean com.google.firebase.firestore.DocumentSnapshot.exists()”
【发布时间】:2020-02-23 13:36:11
【问题描述】:

我在使用 firebase firestore 时得到一个空指针引用并且我的应用程序崩溃了。这是我的代码:

private FirebaseFirestore fstore=FirebaseFirestore.getInstance();

private DocumentReference documentReference=fstore.collection("users").document("17030121084");
@Override
    protected void onStart(){
        super.onStart();
        documentReference.addSnapshotListener(this, new EventListener<DocumentSnapshot>() {
            @Override
            public void onEvent(@Nullable DocumentSnapshot documentSnapshot, @Nullable FirebaseFirestoreException e) {

                if (documentSnapshot.exists()){
                    String semester=documentSnapshot.getString("sem");
                    sem.setText(semester);
                }
            }
        });
    }

这里的 sem 指的是我在文档 17030121084 中的字段。

有人可以为此提出解决方案吗?

【问题讨论】:

    标签: java android firebase google-cloud-firestore nullpointerexception


    【解决方案1】:

    如果在尝试读取文档时出错,documentSnapshot 变量将为 null。所以你的代码需要检查一下。

    最简单的方法是添加一个简单的null 检查:

    public void onEvent(@Nullable DocumentSnapshot documentSnapshot, @Nullable FirebaseFirestoreException e) {
        if (document != null && documentSnapshot.exists()){
            String semester=documentSnapshot.getString("sem");
            sem.setText(semester);
        }
    }
    

    但是上面的代码还没有处理错误。而且由于在您的情况下显然documentnull,您实际上需要知道错误是什么才能修复它。

    所以这是一个更好的方法:

    public void onEvent(@Nullable DocumentSnapshot documentSnapshot, @Nullable FirebaseFirestoreException e) {
        if (e != null) {
            Log(TAG, "Listen failed.", e);
            return;
        }
    
        if (documentSnapshot.exists()){
            String semester=documentSnapshot.getString("sem");
            sem.setText(semester);
        }
    }
    

    请注意,此代码与 listening for documents 上的文档中的内容非常匹配,因此我强烈建议您花一些时间在那里。

    【讨论】:

    • 谢谢,我更改了权限,它对我有用。
    猜你喜欢
    • 2018-07-24
    • 2017-06-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-02-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多