我收到了 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 回答
您的应用程序崩溃,因为您没有初始化
QuerySnapshot
并且它为空 .在onCreate中初始化QuerySnapshot
EDIT:
在
QuerySnapshot
&Exception
之前给出@Nullable
并在之后给出错误回调 .OR 检查弗兰克建议的答案 . 一旦您想要停止收听更新,取消订阅是一个很好的做法 .
看起来传递到
onEvent
的QuerySnapshot
可以为null,并且您必须在代码中防范它:documentSnapshots
变为null的原因可能是,一旦用户退出,您的应用程序将无法访问此代码正在观察的特定数据 . 在签署用户之前,您可能需要首先考虑detaching all listeners .