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): I need t
Solution 1:
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:
DatabaseReferencemDatabasePlayers= FirebaseDatabase.getInstance().getReference().child("Players");
QuerymDatabaseHighestPlayer= mDatabasePlayers.child("Scores").orderByChild("rank").limitToLast(1);
mDatabaseHighestPlayer.addValueEventListener(newValueEventListener() {
@OverridepublicvoidonDataChange(DataSnapshot dataSnapshot){
for (DataSnapshot childSnapshot: dataSnapshot.getChildren()) {
StringKey= childSnapshot.getKey();
Toast.makeText(main.this,Key,Toast.LENGTH_LONG).show();
}
}
@OverridepublicvoidonCancelled(DatabaseError databaseError) {
throw databaseError.toException(); // don't swallow errors
}
});
Solution 2:
Change this line:
QuerymDatabaseHighestPlayer= mDatabasePlayers.child("Scores").orderByChild("rank").limitToFirst(1);
with
QuerymDatabaseHighestPlayer= mDatabasePlayers.child("Scores").child(scoreId).orderByChild("rank").limitToFirst(1);
In which scoreId
is the unique id generated bu the push()
method.
Post a Comment for "Firebase Return Child That Have Biggest Value"