I am trying to remove my ChildEventListener observer when I leave the activity as shown below in my onPause method. Basically my problem is when I leave the activity and return to it my childListener gets incremented by one so depending on how many times i leave the activity and return to it my System.out.println will print to console "onChildAdded" and "onChildRemoved" multiple times and I only want it to be called once. Any help on how to terminate my Listeners when i leave the activity, thank you in advance :)
// Connect to DB
private DatabaseReference mDataBase;
private FirebaseAuth mAuth = FirebaseAuth.getInstance();
String currentUser_UID = mAuth.getCurrentUser().getUid();
ChildEventListener childListener;
@Override
protected void onCreate(Bundle savedInstanceState) {
mDataBase = FirebaseDatabase.getInstance().getReference();
childListener = mDataBase.child("Users").addChildEventListener(new ChildEventListener() {
@Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
String savedCardUser = (String) dataSnapshot.child("Card").getValue();
System.out.println("onChildAdded");
}
@Override
public void onChildChanged(DataSnapshot dataSnapshot, String s) {
}
@Override
public void onChildRemoved(DataSnapshot dataSnapshot) {
System.out.println("onChildRemoved");
}
@Override
public void onChildMoved(DataSnapshot dataSnapshot, String s) {
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
@Override
protected void onPause() {
super.onPause();
mDataBase.removeEventListener(childListener);
}
Edit
If it wasn't the simplest thing :) had to add the child() paths works perfect now. Successfully removes my Listeners
mDataBase.child("Card").removeEventListener(childListener);