Luis Aguilar
Luis Aguilar

Reputation: 745

Make a top ten of the best players using Firebase Database

I am new in Firebase Database and I'm struggling with this problem. What I want to achieve is: show a top ten of the best players based on their "hits". I know I could use firebase queries but I don't know how to use them.

enter image description here

Query mquery =
                    FirebaseDatabase.getInstance().getReference()
                            .child("player")
                            .orderByChild("hits");

            mquery.addValueEventListener(new ValueEventListener() {
                @Override
                public void onDataChange(DataSnapshot dataSnapshot) {
                    for (DataSnapshot postSnapshot: dataSnapshot.getChildren()) {
                        UserInformation score=postSnapshot.getValue(UserInformation.class);

                        Map<String, Object> map = (Map<String, Object>) postSnapshot.getValue();

                        Log.d("test"," values is " + score.getHits());
                    }
                }

                @Override
                public void onCancelled(DatabaseError databaseError) {

                }
            });

Every time I run this code I get the next error:

Failed to convert value of type java.util.HashMap to String

Upvotes: 1

Views: 565

Answers (1)

Frank van Puffelen
Frank van Puffelen

Reputation: 599946

I think you missing two things:

  1. a limitToLast(10) so that you get the 10 highest scores only
  2. use .orderByChild("easy/hits"), since that's where the value is stored

So:

Query mquery = FirebaseDatabase.getInstance().getReference()
                        .child("player")
                        .orderByChild("easy/hits")
                        .limitToLast(10);

Note that a Map is inherently unordered, so not a good structure to keep an ordered list in. You'll want to use some List structure for that.

public void onDataChange(DataSnapshot dataSnapshot) {
    List<String> names = new LinkedList<String>();
    for (DataSnapshot postSnapshot: dataSnapshot.getChildren()) {
        String key = postSnapshot.getKey();
        String name = postSnapshot.child("easy/name").getValue(String.class);
        names.add(0, name);
    }
}

You'll note that I call names.add(0, name). This ensures that the results end up in the list in descending order, like you'd expect on a leaderboard.

Upvotes: 4

Related Questions