0

I have a people model that has a name, age, and sex. Now, I want to filter by age and get only the name of the oldest person. However, I can't find a way to do that. This is how my data looks like. People Node

So far I have been able to get all the person's information like this:

                Query oldest = FirebaseDatabase.getInstance().getReference("people").orderByChild("age").limitToLast(1);
                    oldest.addListenerForSingleValueEvent(new ValueEventListener() {
                    @Override
                    public void onDataChange(DataSnapshot dataSnapshot) {
                        for(DataSnapshot datas: dataSnapshot.getChildren()){
                            People peolpe =  datas.getValue(People.class);
            
                        }
                        displayName(people.name);
            
                    }
                    @Override
                    public void onCancelled(DatabaseError databaseError) {
                        Toast.makeText(MainActivity.this, ""+databaseError, Toast.LENGTH_SHORT).show();
                    }
                });
Alex Mamo
  • 130,605
  • 17
  • 163
  • 193
Callie
  • 11
  • 4

1 Answers1

0

When you are using the following query:

Query oldest = FirebaseDatabase.getInstance().getReference("people").orderByChild("age").limitToLast(1);

You are getting the youngest person because this is Firebase's default behavior. If you want to reverse the order, you can either do it on the client-side, or you can make those numbers negative, instead of positive. So having the negative values for the age property, you'll get now the desired results, as the oldest person will have "-25" years. The only thing that remains to be done is to remove that negative sign in your code. Now you're good to go because there is nothing that should be changed in your query.

Alex Mamo
  • 130,605
  • 17
  • 163
  • 193