问题
Reading the documentation, It seems childEventListener does not fire when the path does not exist.
This is a problem since I want to display a message to the user that there is no data.
I could add a valueEventListener like in this answer but I'm limiting the query to the latest value i.e query.limitToLast() and a valueEventListener doesn't limitTolast but gets all the data in the path.
Example, I have:
posts
{
$userid
{
$postid {
post_content:content
timestamp:1234567
}
$postid {
post_content:content
timestamp:1234567
}
$postid {
post_content:content
timestamp:1234567
}
$postid {
post_content:content
timestamp:1234567
}
}
}
I'm only interested in the latest post so I do firebaseRef.child(users).child(userid).limitToLast(1).addChildEventListener but the user might not have posts yet and childEventListener does not fire in that case.
回答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(new ChildEventListener() {
void onChildAdded(DataSnapshot snapshot, String previousChildKey) {
...
}
...
});
query.addValueEventListener(new ValueEventListener() {
void onDataChange(DataSnapshot snapshot) {
if (!snapshot.exists()) {
// TODO: handle the "no data available" scenario
}
});
});
回答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 .
来源:https://stackoverflow.com/questions/39671076/firebase-childeventlistener-return-value-when-path-does-not-exist