6

Here is my Firebase data

{
"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": {}
}
}
}

I want to count the number of keys available under Technology When I use the below code , gets count = 7 , but there is 20 keys available under Technology

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

            }
        });

So.. How to implement it??

Ashique bzq
  • 541
  • 2
  • 9
  • 21
  • Maybe you can use the addListenerForSingleValueEvent() listener that fetches all the data once. Then you can use the snapshot to count the children with getChildrenCount() . Did you try it? – user2399432 Apr 25 '17 at 09:19
  • This question already has an answer here: [Firebase android count children and store it in a variable](http://stackoverflow.com/questions/41163512/firebase-android-count-children-and-store-it-in-a-variable?rq=1) – Praveen Kumar Apr 25 '17 at 10:02

1 Answers1

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

            }
        });
Alex Mamo
  • 130,605
  • 17
  • 163
  • 193
Rajesh Satvara
  • 3,842
  • 2
  • 30
  • 50