Skip to content Skip to sidebar Skip to footer

Firebase Childeventlistener Return Value When Path Does Not Exist

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

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"