I have a listener set on the root of my Firebase Database -
database = FirebaseDatabase.getInstance();
rootDB = database.getReference();
I have a listener set up as follows -
groupListener = (new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
Log.i("ValueEventListener", "Count :" + dataSnapshot.getChildrenCount());
.... more code...
I attach the listener as below -
rootDB.addValueEventListener(groupListener);
Then as I load a new activity, I want this to stop listening so I use -
rootDB.removeEventListener(groupListener);
It seems to keep listening, can anyone tell me what I've done wrong?
I know I can use a single event listener but I want it to keep monitoring while it's in this activity but not when in other activities.
Thanks!
three suggestions:
1. You may be adding listener more than once.
If a listener has been added multiple times to a data location, it is called multiple times for each event, and you must detach it the same number of times to remove it completely. (from here)
2. The listener you are adding may not be the same one you are removing. Here CASE 1 will remove the listener while CASE 2 will not:
//CASE 1:
ValueEventListener listener = new ValueEventListener() {....}
databaseRef.addValueEventListener(listener);
databaseRef.removeEventListener(listener);
//CASE 2:
public ValueEventListener listener(){
return new ValueEventListener() {....}
}
databaseRef.addValueEventListener(listener());
databaseRef.removeEventListener(listener());
3. As a workaround, you can set a boolean and change it's value when you want to stop/start listening:
groupListener = new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
if(isListening){
//...
}
}
Hope one of them helps..
This is maddening!
From what I can tell, the removeEventListener
method is asynchronous and will eventually be removed. But if you are trying to quickly switch from one DatabaseReference
to another (such as a $uid
path), then you're going to have the duplicate calls. I'm not found a synchronous way to resolve this.
After hours of debugging and much of my live stolen from me, I extended the ChildEventListener
interface, add the isListening
functionality that @Ahmed mentions above. Now I see that while initially there are duplicate calls to onChildAdded
, they do eventually subside.
GLWY!!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With