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!
You're doing two things wrong:
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With