Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 there are no children, nothing will fire.

like image 592
Bjørn Skagen Avatar asked Dec 15 '16 01:12

Bjørn Skagen


People also ask

What is getKey () in Firebase?

public String getKey () Returns. The key name for the source location of this snapshot or null if this snapshot points to the database root.

Is Firebase DB NoSQL?

The Firebase Realtime Database is a cloud-hosted NoSQL database that lets you store and sync data between your users in realtime.


2 Answers

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 getChildrenCount
        if(!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) {
    }
});
like image 97
Linh Avatar answered Sep 24 '22 02:09

Linh


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

 searchFirebaseRef.addListenerForSingleValueEvent(new ValueEventListener() {
        @Override
        public void onDataChange(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   

         }


      }
        @Override
        public void onCancelled(DatabaseError databaseError) {


        }

    });

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

like image 31
Vinoth Vino Avatar answered Sep 23 '22 02:09

Vinoth Vino