I have this for Firestore.
FirebaseFirestore db = FirebaseFirestore.getInstance();
CollectionReference ref = db.collection("app/appdata/notifications");
ref.addSnapshotListener((snapshot, e) -> {
if (e != null) {
Log.w(TAG, "Listen failed.", e);
return;
}
for (DocumentSnapshot x : snapshot.getDocuments()) {
System.out.println(x.getData());
}
});
But I don't want to use that loop, instead I need to only get the new children. I'd like something like the following as seen in the Realtime Db.
ref.addChildEventListener(new ChildEventListener() {
@Override
public void onChildAdded(DataSnapshot dataSnapshot, String prevChildKey) {
Post newPost = dataSnapshot.getValue(Post.class);
System.out.println("Author: " + newPost.author);
System.out.println("Title: " + newPost.title);
System.out.println("Previous Post ID: " + prevChildKey);
}
@Override
public void onChildChanged(DataSnapshot dataSnapshot, String prevChildKey) {}
@Override
public void onChildRemoved(DataSnapshot dataSnapshot) {}
@Override
public void onChildMoved(DataSnapshot dataSnapshot, String prevChildKey) {}
@Override
public void onCancelled(DatabaseError databaseError) {}
});
You need to use .getDocumentChanges()
on the QuerySnapshot object to get the list of changes since the last snapshot. This is equivalent to the child-change events in Realtime Database. For example:
FirebaseFirestore db = FirebaseFirestore.getInstance();
CollectionReference ref = db.collection("app/appdata/notifications");
ref.addSnapshotListener((snapshot, e) -> {
if (e != null) {
Log.w(TAG, "Listen failed.", e);
return;
}
for (DocumentChange dc : snapshots.getDocumentChanges()) {
switch (dc.getType()) {
case ADDED:
// handle added documents...
break;
case MODIFIED:
// handle modified documents...
break;
case REMOVED:
// handle removed documents...
break;
}
}
}
});
See https://firebase.google.com/docs/firestore/query-data/listen#view_changes_between_snapshots for more details.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With