android firebase - 获得儿童计数

时间:2017-04-25 09:07:37

标签: android firebase firebase-realtime-database

以下是我的Firebase数据

{
"ques": {
"Chemistry": {},
"Countries": {},
"Film": {},
"Geography": {},
"General Knowledge": {},
"Information Technology": {},
"Physics": {},
"Sports": {},
"Technology": {
"-Ki0y2ojhgAkDKVFostV": {},
"-Ki0ySAkiILNo2WSM7EO": {},
"-Ki1-8R-5gfHJGl9bDYC": {},
"-Ki1-fP2HlW0ejzVOGnD": {},
"-Ki1-vihF3xgP81UPT5t": {},
"-Ki10DSBPWIK0SAv5v8V": {},
"-Ki11-pLXVWZlv0XbKpp": {},
"-Ki11al-z6_MDBdpLGh7": {},
"-Ki11pxZvjvIl68UhVRc": {},
"-Ki124jOsYpy9bWpc7Yo": {},
"-Ki12oDiad-7X6UBTtBv": {},
"-Ki133GHJeys-J0vtdI9": {},
"-Ki13Iq62Ly_tx4tcxKa": {},
"-Ki13e4pp1Xnq7tnYa4N": {},
"-Ki142gU6ZHRkE34r0u3": {},
"-Ki14GswYf_lEji5a2PX": {},
"-Ki14WZpH5w5jnB4mZF1": {},
"-Ki14tX__g6VdmHJHi-g": {},
"-Ki15JghcU73RtW5zacV": {},
"-Ki15c91cOoRoR7h5aTL": {}
}
}
}

我想计算Technology下可用的密钥数量 当我使用下面的代码时,得到count = 7,但在Technology

下有20个密钥可用
Query countQuery = countRef.child("ques").child("Technology");
countQuery.addChildEventListener(new ChildEventListener() {
            @Override
            public void onChildAdded(DataSnapshot dataSnapshot, String s) {


                questionCount = (int) dataSnapshot.getChildrenCount();
                tQuestionNoShow.setText(""+questionCount);

            }

            @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 个答案:

答案 0 :(得分:11)

  Firebase.setAndroidContext(this);
  DatabaseReference fbDb = null;
  if (fbDb == null) {
      fbDb = FirebaseDatabase.getInstance().getReference();
  }


  fbDb.child("ques/Technology")
      .addListenerForSingleValueEvent(new ValueEventListener() {
           @Override
           public void onDataChange(DataSnapshot dataSnapshot) {
               // get total available quest
                int size = (int) dataSnapshot.getChildrenCount();
            }
            @Override
            public void onCancelled(DatabaseError databaseError) {

            }
        });