Search code examples
androidsortingactionbarsherlock

Broken sort after search


I wrote a simply app with ListView and ActionBarSharlock (ABS). I have my objects, custom ArrayAdapter, in my ABS I have SearchView and drop down list, now about my problem, if I'm searching something before sort all works fine, but after "search" a sort function is broken.

    public boolean onNavigationItemSelected(int position, long itemId) {
                        switch (position) {
                        case 0:
                            countryArrayAdapter.sort(new SortByAZ());
                            break;
                        case 1:

...................


        SearchView.OnQueryTextListener queryTextListener = new SearchView.OnQueryTextListener() {
            public boolean onQueryTextChange(String newText) {
                countryArrayAdapter.getFilter().filter(newText);
                return true;
            }

What I do wrong?


Solution

  • What I do wrong?

    Nothing. The problem is ArrayAdapter is buggy.

    Relevant code from API 17 implementation of ArrayAdapter:

    public void sort(Comparator<? super T> comparator) {
        synchronized (mLock) {
            if (mOriginalValues != null) {
                Collections.sort(mOriginalValues, comparator);
            } else {
                Collections.sort(mObjects, comparator);
            }
        }
        if (mNotifyOnChange) notifyDataSetChanged();
    }
    
    public T getItem(int position) {
        return mObjects.get(position);
    }
    

    As you can see, it sometimes sorts different list. Actually after you first filter it, mOriginalValues becomes not null.

    There is a workaround for it. You have to filter it again with the same text value after every change (sort, insert, etc.) to the list.

    I always suggest not to use ArrayAdapter and instead build on BaseAdapter with your own Filter implementation when needed.

    Edit:

    Just found this is a known issue for a few years already: http://code.google.com/p/android/issues/detail?id=9666