【发布时间】:2018-06-17 10:28:30
【问题描述】:
我有一个托管片段的活动。在片段中,我有一个方法可以帮助我从数据库中获取数据,如下所示:
public void readData(ListCallback listCallback) {
DocumentReference listIdRef = rootRef.collection("lists").document(listId);
listIdRef.addSnapshotListener((snapshot, e) -> {
if (snapshot != null && snapshot.exists()) {
ListModel listModel = snapshot.toObject(ListModel.class);
String direction = listModel.getDirection();
Log.d("TAG", direction);
}
});
}
当我第一次启动活动时,一切正常,direction 字段的值在 logcat once 中打印。如果direction的值改变,onEvent()方法被触发,direction字段的值再次打印到logcat中。当我离开活动并返回时,第一次打印 direction 的值,但如果更改了 direction 的值,而不是打印一次值,而是打印两次。如果我离开活动并再次回来做同样的事情,则该值将打印 3 次。我怎样才能阻止这种情况发生?我每次只需要打印一次。
提前致谢!
【问题讨论】:
-
direction是什么?何时/为什么要更改? -
暂停活动时是否要移除监听器?如果没有更多代码,我只能假设您只是一遍又一遍地添加侦听器,但从不删除它
-
@GhostDerfel 我在
onStart()方法中使用firestoreRecyclerAdapter.startListening();,在onStop()中使用firestoreRecyclerAdapter.stopListening()。我还需要什么吗? -
@MikeSpeed
direction是一个字符串字段,可以有不同的值。这就是改变的原因。 -
@IoanaP.check the SnapshotListener documentation firebase.google.com/docs/firestore/query-data/… 如果您不再需要该侦听器,则应该删除它,或者只需检查是否已经为您的活动注册了一个侦听器
标签: java android firebase google-cloud-firestore