首页 文章

尝试调用虚方法:空对象引用

提问于
浏览
-2

我收到了 Null Object Reference ,当我退出时应用程序崩溃了 .

码:

//Get Comments Count
firebaseFirestore.collection("Posts/" + postId + "/Comments").addSnapshotListener(new EventListener<QuerySnapshot>() {
    @Override
    public void onEvent(QuerySnapshot documentSnapshots, FirebaseFirestoreException e) {

        if (!documentSnapshots.isEmpty())
        {
            int count = documentSnapshots.size();
            holder.updateCommentsCount(count);
        }
        else if(documentSnapshots.isEmpty())
        {
            holder.updateCommentsCount(0);
        }
    }
});

错误:

尝试在空对象引用上调用虚方法'boolean com.google.firebase.firestore.QuerySnapshot.isEmpty()'

2 回答

  • 0

    您的应用程序崩溃,因为您没有初始化 QuerySnapshot 并且它为空 .

    private QuerySnapshot querySnap;
    

    在onCreate中初始化QuerySnapshot

    querysnap = new QuerySnapshot (this, " ");
    

    EDIT:

    QuerySnapshotException 之前给出 @Nullable 并在之后给出错误回调 .

    public void onEvent(@Nullable QuerySnapshot documentSnapshots, @Nullable FirebaseFirestoreException e) {
    if (e != null) {
              //          Log.w(TAG, "this is the error", e);
                        return;
                    }
            if (!documentSnapshots.isEmpty())
                {
    

    OR 检查弗兰克建议的答案 . 一旦您想要停止收听更新,取消订阅是一个很好的做法 .

  • 0

    看起来传递到 onEventQuerySnapshot 可以为null,并且您必须在代码中防范它:

    public void onEvent(QuerySnapshot documentSnapshots, FirebaseFirestoreException e) {
        if (documentSnapshots == null || documentSnapshots.isEmpty())
        {
            holder.updateCommentsCount(0);
        }
        else
        {
            int count = documentSnapshots.size();
            holder.updateCommentsCount(count);
        }
    }
    

    documentSnapshots 变为null的原因可能是,一旦用户退出,您的应用程序将无法访问此代码正在观察的特定数据 . 在签署用户之前,您可能需要首先考虑detaching all listeners .

相关问题