j22purikas j22purikas - 4 months ago 77
Android Question

After chaning child in FirebaseDatabase.getInstance().getReference().child(userID), it's still listening previous child

If i change child in FirebaseDatabase.getInstance().getReference().child("userID"), why it is still keep listening previous childs. Let say i have user1, user2 and user3. If i logIn with user1, it is listening only user1 values, after i logIn with user2, it is listening user1 and user2 values and if i logIn with user3, it is listening user1, user2, and user3 values. Why firebase keeps listening previous childs. If i logIn first time with user1, it dosent listening user2 and user3 values.

protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_logged_in);

databaseReference = FirebaseDatabase.getInstance().getReference().child(userID);
databaseReference.addChildEventListener(new ChildEventListener() {
@Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {


}

@Override
public void onChildChanged(DataSnapshot dataSnapshot, String s) {
Toast.makeText(this,dataSnapshot.getValue(String.class),Toast.LENGTH_LONG).show();


}

@Override
public void onChildRemoved(DataSnapshot dataSnapshot) {

}

@Override
public void onChildMoved(DataSnapshot dataSnapshot, String s) {

}

@Override
public void onCancelled(DatabaseError databaseError) {

}
});
}

Answer

You need to keep a reference of the ChildEventListener you're adding to your databaseReference, and then call if (childEventListener != null) databaseReference.removeEventListener(childEventListener); on the onStop() method of your activity.

Comments