Reputation: 60909
I am having a weird issue. I have an ArrayAdapter which I am sorting. This displays properly on my screen, however when I check the actual data source, the contents have not been sorted. How can I ensure that sorting my ListAdapter will also sort my data source?
Collections.sort(quotes, new PercentChangeComparator()); //sort my data source (this isn't necessary)
quotesAdapter.sort(new PercentChangeComparator()); //sort my ListAdapter
Toast toast = Toast.makeText(getApplicationContext(),quotes.get(0).getSymbol(), Toast.LENGTH_SHORT);
toast.show(); //this shows that my data source hasn't been updated, even though my ListAdapter presents my ListView in the correctly sorted order.
For example:
If my data source is [10,9,1,20]
after sorting my ListView will show [1,9,10,20]
but the data source will still be [10,9,1,20]
How can I resolve this?
Upvotes: 3
Views: 3607
Reputation: 38334
It's the other way round: sorting your data source will order the ArrayAdapter.
I assume you've done something like this before.
ArrayList<PercentChangeComparator> quotes = getQuotesFromSomewhere();
QuotesAdapter quotesAdapter = new QuotesAdapter(this, R.layout.xxx, quotes);
Then, if you sorted quotes, notifying the adapter that the dataSet has changed should sort the list
Collections.sort(quotes, new PercentChangeComparator());
quotesAdapter.notifyDataSetChanged();
This is working for me, I hope it helps.
One important thing: if you recreate the source array (quotes in this specific example), the Adapter won't read further changes. Thus, if you need to modify the content of your ListView, do:
quotes.clear();
quotes.add(...);
quotes.add(...);
Also, make sure you implemented correctly the Comparator. If you execute this
Collections.sort(quotes, new PercentChangeComparator());
and quotes isn't sorted, then the problem isn't related to the Adapter but to the comparation.
Upvotes: 4