0

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) { } }); } } 
1
  • ValueEventListener works like this only . There is a ChildEventListener you might need this one . Commented Mar 30, 2021 at 12:30

1 Answer 1

1

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); 
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.