I have a button that should sort a ListView using a custom adapter. The button listener is as follows:
collectionSort.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
sortOrder = -sortOrder;
Log.d("DBGINF", "Sort Order: " + sortOrder);
m.sortByTitles(sortOrder);
m.notifyDataSetChanged();
});
The sort order changes as it should, and the data in the array is sorted, the actual view is never updated by the notifyDataSetChanged though. Here’s the sortByTitles() method:
public void sortByTitles(int dir) {
if (dir > 0) {
sort(new StringComparator());
} else if (dir < 0) {
sort(new ReverseStringComparator());
}
Log.d("Data Set: ", this.getItem(0) + "");
}
The notifyDataSetChanged() doesn’t ever update the view inside an OnClickListener, but always works properly outside one of the OnClickListeners. What am I doing wrong?
EDIT
Here is the constructor in the Adapter class:
public MainMenuArrayAdapter(Context context, CollectionObject[] objects) {
super(context, R.layout.mainmenurow, objects);
myContext = context;
}
And here’s how it gets initialized in the onCreate() method of the Activity:
CollectionObject[] sample = new CollectionObject[] { c1, c2, c3, c4, c5, c6 };
final MainMenuArrayAdapter m = new MainMenuArrayAdapter(this, sample);
Where c1 – c6 are just some temporary CollectionObjects for testing.
What kind of adapter are you extending? I think you are actually sorting a copy of the items in your adapter. Are you setting myCollections in the adapter again? Btw if you extend ArrayAdapter keep in mind that the adapter itself has a sort method which accept your own comparator.
EDIT:
I wrote a super stupid example with a custom adapter and sorting, you can press menu for sorting items. Hope it will help!
list_item.xml
main_menu.xml (under res/menu)