Firebase DB: Check if node has no children?

前端 未结 2 1637
情深已故
情深已故 2020-12-19 04:34

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 wo

2条回答
  •  情歌与酒
    2020-12-19 04:57

    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) {
        }
    });
    

提交回复
热议问题