What happens if a firebase url doesnot exist and we try to add a listener to it?

后端 未结 1 743
萌比男神i
萌比男神i 2020-12-21 20:06

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

1条回答
  •  一整个雨季
    2020-12-21 20:13

    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()
            }
        }
    }
    

    0 讨论(0)
提交回复
热议问题