Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Organize HashMap by value (Firebase Database Snapshot)

New at Java programming and couldn't find an answer for this.

I created a Firebase Database for a small game I built and managed to get the scores to be stored correctly. Now I want to build the leaderboard with the top ten scores. The database itself is indexed by top scores, and I get the top 10 scores with:

mDatabase.child(gameName).child("Score").limitToFirst(10).addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            // Get user value
            HashMap<String,Long> topScores = (HashMap<String, Long>) dataSnapshot.getValue();
....

The problem with that is that (from what I can see) what I receive is a HashMap which I store in topScores. Again, from what I understand so far, HashMaps are unorganized, so when you print it, it looks something like this:

{DummyData1=0, try=0, dummy2=5, lalala=10, Name1=0, try2=0, lala=11, try3=0, la=3, dummy=1}

So, no discernible order.

Finally, the question is how would you recommend I go about ordering the HashMap created in order to store the Key and Value pairs in their corresponding TextView (the top scorer and top score in the first Row of TextViews, and so on).

As a reference, how I plan on showcasing the leaderboard

Thanks!

like image 833
Mariano Molina Avatar asked Mar 12 '23 16:03

Mariano Molina


1 Answers

You're doing two things wrong:

  1. you're not telling Firebase to order the data by any value
  2. you're converting the results to a Map, which is inherently unordered

Assuming that you have this JSON structure under Score (please post the JSON as text next time you ask a question):

Score

The code would be:

mDatabase.child(gameName).child("Score")
         .orderByValue().limitToLast(10).addValueEventListener(new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {
        for (DataSnapshot child: dataSnapshot.getChildren()) {
            System.out.println(child.getKey()+"="+child.getValue(Long.class));
        }

And it will print:

Puf=30

Polarbear0106=42

KatoWulf=60

like image 103
Frank van Puffelen Avatar answered Mar 24 '23 04:03

Frank van Puffelen