Reputation: 853
I have created an Intent service, and in it, I have created a listener, but as addValueEventListener get called three-time
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) {
}
});
}
}
Upvotes: 0
Views: 41
Reputation: 138824
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);
Upvotes: 1