Skip to content Skip to sidebar Skip to footer

Firebase Db: Check If Node Has No Children?

How do I find out if a Firebase DB node has no children? Seems the only way to get data is with listeners, and they only fire when something is added or removed. In other words, if

Solution 1:

You can use addValueEventListener, and in onDataChange you will have some way to check no children. The addValueEventListener will work because arcoding this docs

This method is triggered once when the listener is attached and again every time the data, including children, changes

ref.addValueEventListener(new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot snapshot) {
        // As cricket_007 we also can use hasChildren or getChildrenCountif(!snapshot.hasChildren()){
            // db has no children
        }

        // OR this way
        if(snapshot.getChildrenCount() == 0){
            // db has no children
        }

        // OR this way
        for (DataSnapshot postSnapshot : snapshot.getChildren()) {
            // db has no children
        }
    }

    @Override
    public void onCancelled(FirebaseError firebaseError) {
    }
});

Solution 2:

You can check whether the child is present in Firebase or not by using the getChildrenCount() or exists() method of DataSnapshot.

 searchFirebaseRef.addListenerForSingleValueEvent(newValueEventListener() {
        @OverridepublicvoidonDataChange(DataSnapshot dataSnapshot) {

        Log.d("FIREBASE",String.valueOf(dataSnapshot.getChildrenCount()));
        String childrenCount = String.valueOf(datasnapshot.getChildrenCount());

       if(childrenCount != null){

          }else{

          //No childrens in Firebase Database
       }

//OR if(!dataSnapshot.exists()){

          //No data   

         }


      }
        @OverridepublicvoidonCancelled(DatabaseError databaseError) {


        }

    });

See this doc for more info. I hope this helps you.

Post a Comment for "Firebase Db: Check If Node Has No Children?"