0

This code works even when I exit the activity and go to another activity. In order to understand this, I went to another activity and deleted the path in Firebase and the application crashed due to the fact that this path no longer exists. I would like to disable this code when I exit the activity, how can I do this?

private void addRoomEventListener() {
        messageRef.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot snapshot) {
                if (role.equals("host:")) {
                    if (snapshot.getValue(String.class).contains("guest:")) {
                        step.setEnabled(true);
                        Toast.makeText(DuelGame.this, "" +
                                snapshot.getValue(String.class).replace("guest:", ""), Toast.LENGTH_SHORT).show();
                    }
                } else {
                    if (snapshot.getValue(String.class).contains("host:")) {
                        step.setEnabled(true);
                        Toast.makeText(DuelGame.this, "" +
                                snapshot.getValue(String.class).replace("host:", ""), Toast.LENGTH_SHORT).show();
                    }
                }
            }

            @Override
            public void onCancelled(@NonNull DatabaseError error) {
                messageRef.setValue(message);
            }
        });
    }
Biron1gg
  • 87
  • 1
  • 10

1 Answers1

2

You can save addValueEventLister call in a variable yourListener and then do this when switching to another activity or when the current activity is going to finish ( usually in onPause() or onStop()),

dbref.removeEventListener(yourListener);
Shobhith
  • 505
  • 4
  • 12