Firebase Childeventlistener Return Value When Path Does Not Exist
Solution 1:
If you want to handle both the children and the case where no children exists, you can add both a value and a child listener:
Query query = firebaseRef.child(users).child(userid).limitToLast(1);
query.addChildEventListener(newChildEventListener() {
voidonChildAdded(DataSnapshot snapshot, String previousChildKey) {
...
}
...
});
query.addValueEventListener(newValueEventListener() {
voidonDataChange(DataSnapshot snapshot) {
if (!snapshot.exists()) {
// TODO: handle the "no data available" scenario
}
});
});
The Firebase client is smart enough to only load data once, even if there are multiple listeners like in the above case.
If you want, you can also accomplish this with a single ValueEventListener
like this:
query.addValueEventListener(newValueEventListener() {
voidonDataChange(DataSnapshot snapshot) {
if (!snapshot.exists()) {
// TODO: handle the "no data available" scenario
}
else {
for (DataSnapshotchildSnapshot: snapshot.getChildren()) {
// TODO: handle the child snapshot
}
}
});
});
Since we now get all matching child nodes in snapshot
, we loop over the snapshot.getChildren()
to get the same data as in onChildAdded
.
Solution 2:
Since its impossible to attach a listener to a non existing path, you could try adding a property to your user that sets the number of posts he has. Add a listener to that property and if it changes, then you are certain that indeed the user has a path reference in posts, then you can add a listener to that node and get the query every time a child is added with .childAdded .
Post a Comment for "Firebase Childeventlistener Return Value When Path Does Not Exist"