Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Firebase + Android - Notifications ChildAdded - How to get only New Childs?

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 addChildEventListener onChildAdded apparently is called one time for every existent record and only then actually listens for new childs..

In this answer @kato states that if addChildEventListener is called like ref.endAt().limit(1).addChildEventListener(...) it would get only the newly added records.

It actually only gets one record at a time (I suppose with limit(1)) but it still gets an existant record before listening for added records.

Here's some code:

Initializing the Listener in onCreate():

@Override
public void onCreate() {
    super.onCreate();
    this.handler = new ChildEventListener() {
        @Override
        public void onChildAdded(DataSnapshot dataSnapshot, String s) {
            AllowedGroup ag = dataSnapshot.getValue(AllowedGroup.class);

            postNotif("Group Added!", ag.getName());
        }
        ...rest of needed overrides, not used...

I'm using the AllowedGroup.class to store the records, and postNotif to build and post the notification. This part is working as intended.

Then, onStartCommand():

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    this.f = new Firebase(FIREBASE_URL).child("users").child(this.currentUserUid).child("allowedGroups");
    f.endAt().limit(1).addChildEventListener(handler);
    return START_STICKY;
}

It still returns one existant record before actually listening for newly added childs.

I've also tried querying by timestamp, like so:

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    this.f = new Firebase(FIREBASE_URL).child("users").child(this.currentUserUid).child("allowedGroups");
    f.startAt(System.currentTimeMillis()).addChildEventListener(handler);
    return START_STICKY;
}

Hoping that it would only get records set after the service was started. It doesn't get existant records, but doesn't even get newly added childs.

EDIT:

I've also thought of something like getting into memory first all of the existant records, and conditionally post a notification if the record brought by onChildAdded does not exist on the previously gathered list, but that seems a bit like overkill, and thought that could be an easier (more API-friendly) way of doing this, am I right ?

Can anyone provide me with some insight on this ? I can't really find anything on the official docs or in any StackOverflow question or tutorial.

Thanks.

like image 242
jsfrocha Avatar asked Jul 12 '14 14:07

jsfrocha


1 Answers

If you have a field modifiedOn, you can index that and setup a query like:

Query byModified = firebaseEndpoint.orderByChild("modifiedOn").startAt(lastInAppTime);
like image 158
prodaea Avatar answered Nov 14 '22 23:11

prodaea