我有这个用于 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());
}
});
但我不想使用那个循环,相反我只需要获取新的 child 。我想要在 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) {}
});
最佳答案
您需要在 QuerySnapshot 对象上使用 .getDocumentChanges()
来获取自上次快照以来的更改列表。这相当于实时数据库中的子更改事件。例如:
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;
}
}
}
});
参见 https://firebase.google.com/docs/firestore/query-data/listen#view_changes_between_snapshots了解更多详情。
关于java - 火力地堡 : Firestore : What is the equivalent of ChildEventListener found in Realtime Database,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46640643/