java - 尝试在空对象引用上调用虚拟方法 'boolean com.google.firebase.firestore.DocumentSnapshot.exists()'

标签 java android firebase google-cloud-firestore nullpointerexception

我在使用 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中的字段。

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

最佳答案

如果尝试读取文档时发生错误,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 文档中的内容非常匹配,所以我强烈建议在那里花一些时间。

关于java - 尝试在空对象引用上调用虚拟方法 'boolean com.google.firebase.firestore.DocumentSnapshot.exists()',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60362736/

相关文章:

java - Geometry.getarea() 和 Polygon.getarea() 的单位是什么?

java - Hazelcast - 为什么入门处理器不使用可移植?

android - 将字符转换为键码

android - 什么是 Android 中的空闲模式

reactjs - firebase.User 在 firebase 版本 9 中

Java getMethods() 与继承层次结构相关

java.io.IOException : An existing connection was forcibly closed by the remote host

android - 从左到右 curl 页面android

javascript - 如何知道异步 forEach 何时完成

ios - 使用 firebase key 执行以下操作会产生过多的成本吗?