如何在addChildEventListener中计算子项? [英] How to count children in addChildEventListener?

查看:75
本文介绍了如何在addChildEventListener中计算子项?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的问题是如何在addChildEventListener中计算子节点?下面的代码在addValueEventListener上工作,并且可以正确计数我的孩子,但是当我使用addChildEventListener时。没用我之所以使用它,是因为该线程:。这样将产生一个DataSnapshot,您可以对其子级进行迭代和计数。


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

        }
    });

解决方案

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.

这篇关于如何在addChildEventListener中计算子项?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆