hsul4n
hsul4n

Reputation: 519

Firebase return child that have biggest value

I am using firebase for a little while but I have stuck at one problem that I want to get the child that have the biggest value:

Example here's my json (edited manually):

{
  "Players" : {
    "Scores" : {
      "-JFUIwudw93dkD" : {
        "rank" : 0
      },
      "-KSFOW833nSfkod" : {
        "rank" : 8
      },
      "-Kk5WfuJ8mlZTPdeUC40" : {
        "rank" : 2
      },
      "-SKKQuyhso83ds" : {
        "rank" : 14
      }
    }
  },

I need to get the child key for the highest rank. So I need the "-SKKQuyhso83ds" child.

I have use this method but It doesn't work:

final DatabaseReference mDatabasePlayers = FirebaseDatabase.getInstance().getReference().child("Players");
    Query mDatabaseHighestPlayer = mDatabasePlayers.child("Scores").orderByChild("rank").limitToFirst(1);
    mDatabaseHighestPlayer.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot){
            //This returns null
            String Key = dataSnapshot.getKey();
            Toast.makeText(main.this,Key,Toast.LENGTH_LONG).show();}
        @Override
        public void onCancelled(DatabaseError databaseError) {}});

but that doesn't work so I'am waiting for some help brothers.

Upvotes: 1

Views: 3435

Answers (2)

Frank van Puffelen
Frank van Puffelen

Reputation: 599946

Firebase queries are ordered ascending. Since you order by rank and limit to the first result, you'll get the lowest score. To get the highest score, use limitToLast(1).

In addition, when you execute a query against the Firebase Database, there will potentially be multiple results. So the snapshot contains a list of those results. Even if there is only a single result, the snapshot will contain a list of one result.

So in total:

DatabaseReference mDatabasePlayers = FirebaseDatabase.getInstance().getReference().child("Players");
Query mDatabaseHighestPlayer = mDatabasePlayers.child("Scores").orderByChild("rank").limitToLast(1);
mDatabaseHighestPlayer.addValueEventListener(new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot){
        for (DataSnapshot childSnapshot: dataSnapshot.getChildren()) {
            String Key = childSnapshot.getKey();
            Toast.makeText(main.this,Key,Toast.LENGTH_LONG).show();
        }
    }
    @Override
    public void onCancelled(DatabaseError databaseError) {
        throw databaseError.toException(); // don't swallow errors
    }
});

Upvotes: 1

Alex Mamo
Alex Mamo

Reputation: 139019

Change this line:

Query mDatabaseHighestPlayer = mDatabasePlayers.child("Scores").orderByChild("rank").limitToFirst(1);

with

Query mDatabaseHighestPlayer = mDatabasePlayers.child("Scores").child(scoreId).orderByChild("rank").limitToFirst(1);

In which scoreId is the unique id generated bu the push() method.

Upvotes: 0

Related Questions