brent
brent

Reputation: 131

Counting Firebase Database nodes in Java

Is there a simple way to count the number of nodes in a specific database in Java?

For example, I have a database with all the current open games and it looks something like this.

openGames {
    game 1:
       Creator username:
       Players joined:
       Game type:
    game 2:
       Creator username:
       Players joined:
       Game type:
}

So for a situation like that in the realtime database, is there a way to count the number of games? So just a way to count the first child in the database. In this case it would return the number 2.

Upvotes: 0

Views: 43

Answers (1)

Martin Lund
Martin Lund

Reputation: 1169

You can use getChildrenCount();

DatabaseReference reference = database.getReference("openGames");

reference.addListenerForSingleValueEvent(new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {
         int nodes = (int) dataSnapshot.getChildrenCount();
    }

    @Override
    public void onCancelled(DatabaseError databaseError) {

    }
}

This should get the amount of nodes if i am not mistaken.

Upvotes: 1

Related Questions