Q:

Stop a method from repeating when activity is closed

    final DatabaseReference db = FirebaseDatabase.getInstance().getReference();
    Query mSeenRef = db.child("Messages").child(MessageSenderId).child(MessageRecieverId).orderByChild("From").equalTo(MessageRecieverId);
    mSeenRef.addValueEventListener(new ValueEventListener(){
        @Override
        public void onDataChange(DataSnapshot dataSnapshot){
            if(dataSnapshot.exists()) {
                for (DataSnapshot ds : dataSnapshot.getChildren()) {
                    String keyId = ds.getKey();
                    DatabaseReference mSendersRef = db.child("Messages").child(MessageSenderId).child(MessageRecieverId).child(keyId);
                    DatabaseReference mRecieversRef = db.child("Messages").child(MessageRecieverId).child(MessageSenderId).child(keyId);
                    Map<String, Object> childUpdates = new HashMap<>();
                    childUpdates.put("Seen", true);
                    mSendersRef.updateChildren(childUpdates);
                    mRecieversRef.updateChildren(childUpdates);

                }
            }
        }
        @Override
        public void onCancelled(DatabaseError databaseError) {
        }
    });

This code is just to set SEEN=true on a basic chat app and it works fine when u open the activity. 
If user A opens the chat activity B gets notified that messages are seen and when the user A is in the chat B still continuously gets notified that A is seeing Bs messages but once A exits the chat the messages B send are still termed as Seen by A even though A isn't inside the activity. 
Only when A closes the app(even from the background) B stops getting his messages to A as seen by A. 
I'm sure the problem is because of this method so I just want to know how to make this method stop executing after the activity is closed. This method is in the onCreate of ChatActivity.

A:

The method will trigger everytime a new message comes since addValueEventListener is listening all the time at your reference for changes, to fix it you can use addListenerForSingleValueEvent but that will trigger only once.
From the docs
Read data once

In some cases you may want a callback to be called once and then
  immediately removed, such as when initializing a UI element that you
  don't expect to change. You can use the
  addListenerForSingleValueEvent() method to simplify this scenario: it
  triggers once and then does not trigger again.

