0

Within my app I often have the need to read data once. I originally started by using the addListenerForSingleValueEvent() method for this, however I ran into problems using this method as it does not work as I wanted when offline capabilities are enabled (see here the issue: Firebase Offline Capabilities and addListenerForSingleValueEvent)

In the question above it is mentioned that a workaround is to use the addValueEventListener() method, however I do not fully understand how to do this (particularly how to remove the ValueEventListener as soon I am finished grabbing the data I need).

Take this method which I created in a standalone class to query the Users node on Firebase where I store the users FCM Token. It seems to have an issue of not returning the latest token from the server everytime.

public class SendFCMMessage {
    String userToken;
    String currentUser;
    String userName;
    ValueEventListener userListener;
    public void sendMessage(final String contactNumber) {

      final DatabaseReference ref = FirebaseDatabase.getInstance().getReferenceFromUrl(link).child("Users").child(contactNumber);
        userListener = new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {
                User user = dataSnapshot.getValue(User.class);
                userToken = user.getToken();
                // Send FCM Message after getting user token and then remove event listener
                ref.removeEventListener(userListener);
            }

            @Override
            public void onCancelled(DatabaseError databaseError) {
                Log.d("TAG", "Something terrible went wrong: " + databaseError);
            }
        };
        ref.addValueEventListener(userListener);
    }
}

If I remove the line

ref.removeEventListener(userListener);

Then this code works fine, however I would like to know how I could remove the ValueEventListener as soon as I receive the data I need?

Thanks, R

Community
  • 1
  • 1
Riley MacDonald
  • 453
  • 1
  • 4
  • 15

1 Answers1

0
ValueEventListener vel; //Declared Global

Listen your DatabaseReference like this;

vel = yourDatabaseReference.addValueEventListener(new ValueEventListener() {
    @Override
    public void onDataChanged(DataSnapshot dataSnapShot) {
        //Do your stuff here. I suggest you create another method for this if you don't want a problem with inner class.
        //For example, workDataSnapshot(DataSnapshot dataSnapShot) <-- Work here
        yourDatabaseReference.removeEventListener(vel);
    }
    @Override
    public void onCancelled(DatabaseError databaseError) {

    }
});

Hope it helps you.