Firebase实时数据库跟踪更改
问题描述:
我正在尝试在活动的onStart方法中跟踪数据库中的所有更改,但以下代码仅在firebase树的第一个行更改时起作用:
I am trying to track all changes in the database in onStart method of an activity, but the following code works only when the first "row" of the firebase tree is changed:
mDatabase = FirebaseDatabase.getInstance().getReference();
mDatabase.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot snapshot) {
for (DataSnapshot child : snapshot.getChildren()) {
System.out.println(child.getKey() + " : " + child.getValue());
}
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
我试图通过为每个孩子创建一个监听器来分别跟踪每个孩子,但它只适用于第一个孩子。如何跟踪所有这些更新?谢谢。
I tried to track each child separately by creating one listener for each child, but it worked only for the first child as well. How can I track updates for all of them? Thank you.
更新。树中有3个孩子:
Update. There are jsut 3 childs in the tree:
我需要能够看到何时更新它们。
I need to be able to see when any of them are updated.
答
尝试使用addChildEventListener:
Try using addChildEventListener:
getDatabase().getReference().addChildEventListener(new ChildEventListener() {
@Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
}
@Override
public void onChildChanged(DataSnapshot dataSnapshot, String s) {
}
@Override
public void onChildRemoved(DataSnapshot dataSnapshot) {
}
@Override
public void onChildMoved(DataSnapshot dataSnapshot, String s) {
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
})