Java – Sorting my ArrayAdapter doesn’t change my data source

Sorting my ArrayAdapter doesn’t change my data source… here is a solution to the problem.

Sorting my ArrayAdapter doesn’t change my data source

I have a strange question. I have an ArrayAdapter that is sorting. This shows correctly on my screen, but when I check the actual data source, the content hasn’t been sorted yet. How do I make sure that sorting my ListAdapter also sorts my data sources?

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 display [1,9,10,20].

But the data source is still [10,9,1,20].

How do I fix it?

Solution

Conversely: Sorting the data source sorts the ArrayAdapter.

I’m assuming you’ve done something similar before.

ArrayList<PercentChangeComparator> quotes = getQuotesFromSomewhere();
QuotesAdapter quotesAdapter = new QuotesAdapter(this, R.layout.xxx, quotes);

Then, if you sort the quotation marks, you are notified that the adapter dataset has changed and the list should be sorted

Collections.sort(quotes, new PercentChangeComparator());
quotesAdapter.notifyDataSetChanged();

This worked for me, hope it helps you.

One important thing: if you recreate the source array (quotes in this particular example), the adapter will not read further changes. Therefore, if you need to modify the contents of a ListView, do the following:

quotes.clear();
quotes.add(...);
quotes.add(...);

Also, make sure that you implement the comparator correctly. If you perform this

Collections.sort(quotes, new PercentChangeComparator());

And quotes is not sorted, then the problem is not about Adapter, but about comparison.

Related Problems and Solutions