如何从firebase数据库获取子总数

时间:2017-08-10 12:51:13

标签: android firebase firebase-realtime-database

我创建了一个Android应用程序,它以下列方式存储User类的值。

{
  "users" : {
    "Om8VuPSCcvg7d5jsYtZvPTWpm5o1" : {
      "email" : "tavinder12singh@gmail.com",
      "name" : "Ajay",
      "uId" : "Om8VuPSCcvg7d5jsYtZvPTWpm5o1"
    },
    "v1dHuFXkfJYt6fYppICQS6rjxiw2" : {
      "email" : "tavinder123singh@gmail.com",
      "name" : "Tavinder Singh",
      "uId" : "v1dHuFXkfJYt6fYppICQS6rjxiw2"
    }
  }
}

我的用户类:

@IgnoreExtraProperties
public class User implements Parcelable {
    public String uId;
    public String email;
    public String name;

    public User() {

    }

    public User(String uId, String email, String name) {
        this.uId = uId;
        this.email = email;
        this.name = name;
    }

    protected User(Parcel in) {
        uId = in.readString();
        email = in.readString();
        name = in.readString();
    }

    public static final Creator<User> CREATOR = new Creator<User>() {
        @Override
        public User createFromParcel(Parcel in) {
            return new User(in);
        }

        @Override
        public User[] newArray(int size) {
            return new User[size];
        }
    };

    @Override
    public int describeContents() {
        return 0;
    }

    @Override
    public void writeToParcel(Parcel parcel, int i) {
        parcel.writeString(uId);
        parcel.writeString(email);
        parcel.writeString(name);
    }
}

我使用以下代码保存数据

FirebaseUser user = mAuth.getCurrentUser();
DatabaseReference database = FirebaseDatabase.getInstance().getReference();
database.child("users").child(user.uId).setValue(user);

但是当我试图计算“用户”拥有的孩子总数时,我得到的只是0。 我使用以下代码来获取子项的总数:

userReference = FirebaseDatabase.getInstance().getReference().child("users");
userReference.addValueEventListener(new ValueEventListener() {
                @Override
                public void onDataChange(DataSnapshot dataSnapshot) {
                    num = dataSnapshot.getChildrenCount();
                }

                @Override
                public void onCancelled(DatabaseError databaseError) {

                }
            });

我想知道如何获得孩子的总数。

1 个答案:

答案 0 :(得分:4)

试试这个:

userReference = FirebaseDatabase.getInstance().getReference("users");
userReference.addValueEventListener(new ValueEventListener() {
                @Override
                public void onDataChange(DataSnapshot dataSnapshot) {
                    num = dataSnapshot.getChildrenCount();
                }

                @Override
                public void onCancelled(DatabaseError databaseError) {

                }
            });