Search code examples
javaandroidfirebasefirebase-realtime-databaselistener

How to make firebase addValueEventListener to fire only when the data is added to the firebase?


I have created an Intent service, and in it, I have created a listener, but as addValueEventListener get called three-time

  1. first when declared
  2. when data is added
  3. when data is removed

How can I modified it so that I can have events only when the data is added

public class MyIntentServiceForEmploy extends IntentService {


    public MyIntentServiceForEmploy() {
        super("MyIntentServiceForEmploy");
    }

    @Override
    protected void onHandleIntent(Intent intent) {
        DatabaseReference reference = firebase.getAllOnlineOrder();
        reference.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot snapshot) {
                Toast.makeText(MyIntentServiceForEmploy.this, "notiifiicatiion", Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onCancelled(@NonNull DatabaseError error) {

            }
        });
    }
}

Solution

  • You are describing the expected behavior. The "onDataChange" method will fire, first when you open the app, and then every time something in your database changes. If you want for example to be notified only for one type of operation, then you should use a ChildEventListener, as explained in the following lines of code:

    ChildEventListener childEventListener = new ChildEventListener() {
        @Override
        public void onChildAdded(@NonNull DataSnapshot dataSnapshot, @Nullable String s) {
            //Get the added data out from the dataSnapshot object
        }
    
        @Override
        public void onChildChanged(@NonNull DataSnapshot dataSnapshot, @Nullable String s) {}
    
        @Override
        public void onChildRemoved(@NonNull DataSnapshot dataSnapshot) {}
    
        @Override
        public void onChildMoved(@NonNull DataSnapshot dataSnapshot, @Nullable String s) {}
    
        @Override
        public void onCancelled(@NonNull DatabaseError databaseError) {
        Log.d("TAG", databaseError.getMessage()); //Don't ignore potential errors!
    }
    };
    reference.addChildEventListener(childEventListener);