So I\'m trying to sort a simple ArrayAdapter
for ListView. Here\'s what I\'ve tried:
ListView lv;
String[] months = {
\"January\",
You didn't called setAdapter(adapter), after sorting your items.
Use like below
adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, list);
lv.setAdapter(adapter);
adapter.notifyDataSetChanged();
instead of
adapter.clear(); // Useless
adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, list);
adapter.notifyDataSetChanged();
To sort a list, you need to use a Comparator. You need to sort the underlying collections using a comparator that does alphabetical sorting and then notify the list to update itself.
Here's an example of doing this using an ArrayAdapter : https://stackoverflow.com/a/8920348/1369222
Android sort listview alphabetically.
listAdapter = new AppsAdapter(MainActivity.this,R.layout.content_layout,appList);
final Collator col = Collator.getInstance();
listAdapter.sort(new Comparator<ApplicationInfo>() {
@Override
public int compare(ApplicationInfo lhs, ApplicationInfo rhs) {
return col.compare(lhs.loadLabel(packageManager),rhs.loadLabel(packageManager));
}
});
Here is the trick...
private void sortAscending () {
List<String> sortedMonthsList = Arrays.asList(months);
Collections.sort(sortedMonthsList);
months = (String[]) sortedMonthsList.toArray();
}
And for sortAscending, call
sortAscending();
adapter.notifyDatasetChanged();
Similarly, you can implement custom Comparator for sort descending as well...
Hope this helps...:)
Comparator<String> ALPHABETICAL_ORDER1 = new Comparator<String>() {
public int compare(String object1, String object2) {
int res = String.CASE_INSENSITIVE_ORDER.compare(object1.toString(), object2.toString());
return res;
}
};
Collections.sort(your array name, ALPHABETICAL_ORDER1);