问题描述
嘿,我需要在某个时候删除这个监听器,还是它自己被删除?我有这个在我的活动中的一个片段调用,用户可以去另一个视图没有被销毁。因此,不知道如果我以某种方式假设要消除 onDestroy
, onPause
调用?我没有办法删除它,因为它是一个 DatabaseReference
这是代码:
private DatabaseReference mDatabase;
mDatabase.child(projects)。orderByChild(viewCount)。limitToLast(15).addChildEventListener(new ChildEventListener(){
@Override
public void onChildAdded(DataSnapshot dataSnapshot,String s){
您确实需要删除相反生命周期事件中的侦听器。
要删除侦听器,您需要保留:
$ p $ Query query = mDatabase.child (projects)。orderByChild(viewCount)。limitToLast(15);
pre>
ChildEventListener listener = query.addChildEventListener(new ChildEventListener(){...
然后:
$ p $ query.removeChildEventListener(收听);
你可以看到我明确地使用了一个 Query
在这里,因为这是你真正的附加你的听众。但是如果你有一个简单的 DatabaseReference
,那么同样的方法是可用的,因为 DatabaseReference
从继承
。
Hey do I need to remove this listener at some point, or does it get removed on its own? I have this called in a fragment within my activity, and users can go to another view without this one being destroyed. Therefore not sure if I am somehow suppose to remove this in an onDestroy
, onPause
call? I do not see a way to remove it since it is a DatabaseReference
Here is the code:
private DatabaseReference mDatabase;
mDatabase.child("projects").orderByChild("viewCount").limitToLast(15).addChildEventListener(new ChildEventListener() {
@Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
As the answer superman links to show: you indeed will need to remove the listener in the opposite lifecycle event.
To remove a listener, you need to keep the handle that is returned when you call addChildListener()
:
Query query = mDatabase.child("projects").orderByChild("viewCount").limitToLast(15);
ChildEventListener listener = query.addChildEventListener(new ChildEventListener() { ...
And then pass it to removeEventListener()
:
query.removeChildEventListener(listener);
You can see that I explicitly use a Query
here, since that is what you actually attach your listener to. But if you have a plain DatabaseReference
the same methods are available, since DatabaseReference
inherits from Query
.
这篇关于Firebase DatabaseReference没有事件侦听器移除?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!