Reputation: 412
I have a ListView
and I want to sort items by a specific Database value of those items. The value will also be in the item. It will not be a one-time sorting. I mean it will do the sorting every time when the activity is created. I am using an adapter for it.
I've already checked every similar question but I could not find a proper solution.
Is there a way to do it? Thank you very much in advance.
This is the Firebase Database Reference of the value for sorting:
mLobbyDatabaseRef = mLobbyDatabase.getReference().child("usersDatabase/" + uid + "/" + "lobbyDatabase/" + otherUid + "/");
DatabaseReference mLobbyDatabaseKeyRef = mLobbyDatabaseRef.child("lobbyKey");
mLobbyDatabaseKeyRef.setValue(itemKey);
itemKey will be the value to use sorting. It is also accessible from the items.
<TextView
android:id="@+id/lobby_key_textview"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentStart="true"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:text=""
android:textColor="@android:color/transparent"
android:textSize="8sp"/>
Upvotes: 0
Views: 281
Reputation: 1942
Is something like this what you are looking for? Note it has the options of sorting by ascending or descending order, taking advantage of the Collections
class and the setAdapter()
method.
private ListView lv;
private static ArrayList<String> itemKey = new ArrayList<>();
private void sortData(boolean asc)
{
if (asc)
Collections.sort(itemKey);
else
Collections.reverse(itemKey);
lv.setAdapter(new ArrayAdapter(MainActivity.this, android.R.layout.simple_list_item_1, itemKey));
}
If the Collections
class and ArrayList
doesn't work, and if you were referring to an adapter like the FirebaseListAdapter
, then try something like this, using the orderByChild()
method to sort into ascending order:
private ListView lv;
Query queryRef = mLobbyDatabaseRef.orderByChild("itemKey");
FirebaseListAdapter<Your_DB_Name> firebaseListAdapter = new FirebaseListAdapter<Your_DB_Name>(this, Your_DB_Name.class, android.R.layout.simple_list_item_1, queryRef)
{
@Override
protected void populateView(View lobby_key_textview, Your_DB_Name model, int position)
{
String itemKey = String.valueOf(model.getItemKey());
((TextView)lobby_key_textview.findViewById(android.R.id.text1)).setText(itemKey);
}
};
lv.setAdapter(firebaseListAdapter);
Upvotes: 1