I am developing an application in which I ask the user to enter the city and state name and return certain location in that place. But the problem is that if the specified s
The methods in a ChildEventListener
are called when a child is added, changed, removed or moved. On an empty location, none of these events happen, so none of the methods are called.
A ValueEventListener
will be called with an empty value if no value exists at a location. So if you also call addListenerForSingleValueEvent()
, you can detect that the location has no value:
Firebase cityRef = firebase.child("markers").child(state).child(city);
cityRef.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot snapshot) {
if (snapshot.getValue() == null) {
System.out.println("No data exists for "+city);
}
}
@Override
public void onCancelled(FirebaseError firebaseError) {
}
});
If you want to handle the children in the same call, you can just loop over them in onDataChange()
:
public void onDataChange(DataSnapshot snapshot) {
if (snapshot.getValue() == null) {
System.out.println("No data exists for "+city);
}
else {
for (DataSnapshot citySnapshot: snapshot.getChildren()) {
// Do something with citySnapshot.getValue()
}
}
}