How to remove listener from Firebase Realtime Database

The correct way to remove a listener is to remove it accordingly to the life-cycle of your activity using this line of code:

databaseReference.removeEventListener(valueEventListener);

Note that, if you have added the listener in onStart you have to remove it in onStop. If you have added the listener in onResume you have to remove it in onPause. If you have added the listener in onCreate you have to remove it in onDestroy.

But remember onDestroy is not always called.

Edit:

The above databaseReference object can be any object of type DatabaseReference. For instance, if you are listening to real-time updates to a node called users:

DatabaseReference db = FirebaseDatabase.getInstance().getReference();
DatabaseReference usersRef = db.child("users");

The code to remove the lister should look like this:

usersRef.removeEventListener(valueEventListener);

And here is the correct import:

import com.google.firebase.database.DatabaseReference;

Its better to check whether listener is null or has an object, because if the listener object is null there will be a runtime error

if(valueEventListener!=null){
  databaseReference.removeEventListener(valueEventListener);
}