I\'m trying to setup an Android Service in my app that listens for new Childs in a Firebase Ref, and throws a Notification when that happens.
I\'m having issues because
For me the logic was is to have value -"status" for example- which needs to be validated before deciding whether it is really new or was an old record then I set the "status" to a different value so I don't get it next time:
@Override
public void onChildAdded(DataSnapshot dataSnapshot, String previousChildKey) {
if(dataSnapshot.hasChildren()) {
String Id = (String) dataSnapshot.child("user_id").getValue();
String status = (String) dataSnapshot.child("status").getValue();
if (Id != null && Id.equals(storedId) && status != null && status.equals("created")) {
Log.d("INCOMING_REQUEST", "This is for you!");
sessionsRef.child(dataSnapshot.getKey()).child("status").setValue("received");
}
}
}
If you have a field modifiedOn
, you can index that and setup a query like:
Query byModified = firebaseEndpoint.orderByChild("modifiedOn").startAt(lastInAppTime);
I overcome this problem by keeping items of firebase database reference node in a List; and whenever onChildAdded(...)
method is triggered, check if the incoming datasnapshot is in your list or not; if not, then it's new data
In order to achieve this you must meet below conditions:
.push()
method..equals()
method of your model class in order to fulfill the comparison based on this unique value.Here code snippets based on your inputs
Model class
public class AllowedGroup {
private String id;
public static List<AllowedGroup> sGroups;
// reset of fields ...
public AllowedGroup() {
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
@Override
public boolean equals(@Nullable Object o) {
// If the object is compared with itself then return true
if (o == this) {
return true;
}
// Check if o is an instance of AllowedGroup or not
if (!(o instanceof AllowedGroup)) {
return false;
}
// typecast o to AllowedGroup so that we can compare data members
AllowedGroup group = (AllowedGroup) o;
// Compare data based on the unique id
return (group.id).equals(id);
}
}
Listening to firebase added nodes
@Override
public void onCreate() {
super.onCreate();
this.handler = new ChildEventListener() {
@Override
public void onChildAdded(@NonNull DataSnapshot dataSnapshot, @Nullable String s) {
AllowedGroup group = dataSnapshot.getValue(AllowedGroup.class);
if (!AllowedGroup.sGroups.contains(group)) {
// Here you'll receive only the new added values
}
}
// ...rest of needed overrides, not used...
}
}