how do i create a leaderboard from the stats in my firebase realtime database?

To get the top 10 users with the highest score, you can use a query like this:

DatabaseReference usersRef = FirebaseDatabase.getInstance().getReference("Users");
Query top10Query = usersRef.orderByChild("highscore").limitToLast(10);

Then read the matching data with something like this:

top10Query.addValueEventListener(new ValueEventListener() {
    public void onDataChange(DataSnapshot dataSnapshot) {
        for (DataSnapshot userSnapshot: dataSnapshot.getChildren()) {
            Log.i("Firebase", userSnapshot.getKey());
            Log.i("Firebase", userSnapshot.child("highscore").getValue());

    public void onCancelled(DatabaseError databaseError) {
        throw databaseError.toException();

The above will give you the top 10 scores, but in ascending order as Firebase has no option to return results in descending order. To display them in the correct order, you’ll need to reverse the results in your code, or add them to the UI in the inverse order.

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top