-1

What I want to do is to get the number of the children using AddChildEventListener as we can do using addListenerForSingleValueEvent.

I mean

thisRoom.addListenerForSingleValueEvent(new ValueEventListener() {
    @Override
    public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
        int numberOfPlayers = (int) dataSnapshot.getChildrenCount();

Now I can get thisRoom's children but I'm wondering if there's a way to do the same thing using AddChildEventListener.

2 Answers2

2

The methods in a ChildEventListener trigger on the individual child nodes, and don't carry knowledge of the entire result. The only way to get a count of the child nodes in a ChildEventListener is to keep your own counter, incrementing it in onChildAdded, and decrementing it in onChildRemoved. This gives you a running counter: a number that reflects how many children your client-code has already processed.

To get an absolute count of the number of children, use a ValueEventListener. Note that attaching both a ChildEventListener and a ValueEventListener to the same location/query, will only transfer the data once. So there's no penalty to attaching both types of listeners, one for each use-case.

Also see:

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
0

In firebase firestore we can call a method datasnapshot.size(); which returns a Int value, you can try this in firebase realtime. Hope this will help.

Rahul Gaur
  • 1,661
  • 1
  • 13
  • 29