How to count children in addChildEventListener?

泪湿孤枕 提交于 2019-12-24 15:20:05

问题


My problem is how can I count child nodes in addChildEventListener? The code below work on addValueEventListener and It counts my child correctly but when I use addChildEventListener. It doesn't work. The reason why I used this, is because of this thread: Firebase Android count children/ badge. I tried this but It doesn't work somehow in my code.

In this picture, the borrowed books should count as 2 but it returns to 10:

This picture shows my database in firebase:

. The reason why it returns to 10 because it counts the children of the child of user.getUid(). All I want to count is the children of user.getUid()

This is the portion of my code:

databaseReference.child("Mark as Borrowed").child(uid).addChildEventListener(new ChildEventListener() {
        @Override
        public void onChildAdded(DataSnapshot dataSnapshot, String s) {
                String number = dataSnapshot.getChildrenCount()+"";
                btnNumber.setText(number);

        }

        @Override
        public void onChildChanged(DataSnapshot dataSnapshot, String s) {

        }

        @Override
        public void onChildRemoved(DataSnapshot dataSnapshot) {

        }

        @Override
        public void onChildMoved(DataSnapshot dataSnapshot, String s) {

        }

        @Override
        public void onCancelled(DatabaseError databaseError) {

        }
    });

回答1:


Child listeners are triggered once for each child found at the reference you choose, and continually over time as children are added, changed and removed. It will only stop triggering those events when the listener is removed from the reference. It is not a one-time query like a single value event listener.

If you want to know the number of children at a location in a single query, addListenerForSingleValueEvent() on the reference. That will yield a DataSnapshot whose children you can iterate and count.




回答2:


databaseReference.child("Mark as Borrowed").addChildEventListener(new ChildEventListener // then check the uid of the value from snapshot to match your desired uid before update the TextView. This should do the trick, but very inefficient since it will read other users too. As Rosário Pereira Fernandes suggested, what's wrong with ValueEventListener? If you want to deal with each book separately, add a instance variable, each time onChildAdded is called, increase that variable by 1 and do the handling logic.



来源:https://stackoverflow.com/questions/48712548/how-to-count-children-in-addchildeventlistener

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!