How to arrange firebase database data in ascending or descending order?
I have setup a firebase database and I was wondering how I'd make it so that my listView shows my data in ascending or descending order.
For example: if I wanted something thats the most expensive I'd have it at the top of my listView and the cheaper ones at the bottom.
Basically I'm trying to create a ranking activity where I've two seperate listviews that rank by cost and count individually.
This is what I have for my count:
@Override
protected void onStart() {
super.onStart();
itemlists=new ArrayList<String>();
databaseItems.child("items").addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot itemSnapShot : dataSnapshot.getChildren()) {
String itemname=itemSnapShot.child("itemName").getValue().toString();
itemlists.add(itemname);
adapter = new ArrayAdapter(SearchActivity.this,android.R.layout.simple_list_item_1,itemlists);
listFinalCount.setAdapter(adapter);
}
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
If you want to order the results of a Firebase database query, you need to use numbers as values and not Strings. If you keep the Strings, as I see in your screenshot, you need to know that the Strings are ordered lexicographically
and I'm sure this is not what you are looking for.
The simplest way to order data in ascending or descending order, would be on client side. Firebase can order the results in ascending order by a given property by default. There is no method in Firebase to order in descending order but there a few tweaks that can be made.
If you are using a RecyclerView
to display data, the simplest way would be to use the following code:
LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity());
layoutManager.setReverseLayout(true);
layoutManager.setStackFromEnd(true);
recyclerView.setLayoutManager(layoutManager);
This approch will reverse you the order.
Another approach would be to create your own adapter that extends FirebaseListAdapter
and override getItem()
method.
Another approach would be to get the data from the database, add it to a Collection
, a List
would be a good solution and then use Collections.reverse(yourList);
.