The documentation says they both listen to changes at a Firebase database location.
They do almost same thing, though ChildEventListener can be sometimes more flexible: with ChildEventListener you can specify different behavior for 4 actions (onChildAdded
, onChildChanged
, onChildMoved
and onChildRemoved
), while ValueEventListener provides only onDataChanged
.
Also ChildEventListener provides DataSnapshots (immutable copies of the data) at child's location while ValueEventListener provides a DataSnapshot of a whole node.
ValueEventListener gets fired only when that specific value changes, but ChildEventListener listens not only value of that node, but also for all child nodes of tree. Say, you have node, which has one children. ValueEventListener will be triggered when this node changes, but ChildEventListener will also be triggered whenewer child values is changed as well. Documentation says, that you should use ChildEventListener with caution - it can be triggered a lot of times.
these are the key differences between the two
if your database has following records:
-LDU4T1buanVuJrpOYxW
message:"hi stack"
user: "john"
-LDasdfa1buanVuJrpOYxW
message:"hi john"
user: "stack"
1) on new entry:
2) because of a) getting the new record in childeventlistener is
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
Map<String,String> map =(Map) dataSnapshot.getValue();
String message = map.get("message").toString();
because of b) getting the new record in ValueEventListener is
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot data : dataSnapshot.getChildren()) {
.... loop until end
Map<String,String> map = (Map)data.getValue();
String message = map.get("message").toString();
so for example if you don't care what happen when somebody delete the first in ValueEventListener you always get notified but in ChildEventListener you only get notified if you override onChildRemoved.
so it depends on what you want to do. for example in a chat app. you will only care about new messages, you don't want to be reinserting all messages again in your chat room.