The code is pushed to the main thread, how to fix it?

Issue

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);
            }
        });
    }

Solution

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);

Answered By – Shobhith

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published