Reputation: 318
This is my current Firebase database:
Is it possible to sort the users (e.g., M57k..
, kNri..
, ulls..
) based on their rating, while they are already on the database? Or it should be done before it enters the database?
Upvotes: 1
Views: 1999
Reputation: 138824
Storing the rating
as a String
is not the the best option when it comes to sorting data in a Firebase database. If you keep the rating as a String, remember that items are ordered lexicographically
. Let's take an example. If you have used numbers, this is the normal order:
But for strings, this is the normal order:
There is no operator in Firebase and as far as i know, nor in most other databases that allow you to change this behavior. So for that, I strongly recommend you change the data type to Integer
or Long
.
If you already have released the app, but I doubt it, because I see some testing values in your database, you need to know that is something that you can do, even if you are using strings. You can modify the data to get the behavior you want. So, you can store the values that are in the order you need when are sorted lexicographically. You can accomplish that by padding them with zeroes:
Assuming you have changed the type of the rating
field and you want to get a user property, to sort the item by rating, please use the following code:
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference carpentersRef = rootRef.child("AvailableWorkers").child("Carpenters");
Query query = carpentersRef.orderByChild("rating")
ValueEventListener valueEventListener = new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot ds : dataSnapshot.getChildren()) {
String g = ds.child("g").getValue(String.class);
Log.d("TAG", g);
}
}
@Override
public void onCancelled(DatabaseError databaseError) {}
};
query.addListenerForSingleValueEvent(valueEventListener);
The output will be the values of g
property ordered by rating
property.
Upvotes: 3
Reputation: 80914
You can do this:
DatabaseReference ref=FirebaseDatabase.getInstance().getReference().child("AvailableWorkers").child("Carpenters");
Query query=ref.orderByChild("rating").startAt("1");
query.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot datas: dataSnapshot.getChildren()){
String keys=datas.getKey();
}
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
Using the query above it will return the result with rating starting equal to 1,orderByChild("rating").startAt("1");
This String keys=datas.getKey();
will give you the ids of the users according to the query.
Upvotes: 1