Search code examples
androidsortinglistviewandroid-cursoradapterandroid-cursor

How to sort a cursor with variables in android?


I have a ListView (in a ListFrament) with a CursorAdapter which shows different names of places. At the begining, the list was sorted by this names (using ORDER_BY in my query).

Now, I have added to my item_row.xml a TextView containing the distance of the place from the user's position thanks to the latitude/longitude of each place and the LocationManager. And I would like to sort my list of places by this distance (from the nearest to the farthest).

The problem is that I calculate the distance outside the "SQL environment", and there are no methods to sort my Cursor/ListView/Adapter...

Any ideas ?


Solution

  • Use Collections.sort(List, Comparator) with a custom Comparator.

    Example using a class A sorting by the sum of both integer fields:

    import java.util.ArrayList;
    import java.util.Collections;
    import java.util.Comparator;
    import java.util.List;
    
    class A {
        final String name;
        final int someNumber;
        final int someOtherNumber;
    
        A(final String name, final int a, final int b) {
            this.name = name;
            this.someNumber = a;
            this.someOtherNumber = b;
        }
    
        @Override
        public String toString() {
            return this.name;
        }
    }
    
    class YourComparator implements Comparator<A> {
        @Override
        public int compare(A o1, A o2) {
            final int sumO1 = o1.someNumber + o1.someOtherNumber;
            final int sumO2 = o2.someNumber + o2.someOtherNumber;
            return (sumO1 - sumO2);
        }
    }
    
    public class Main {
        public static void main(final String args[]) {
            final List<A> listOfAs = new ArrayList<A>();
            listOfAs.add(new A("Three", 1, 2));
            listOfAs.add(new A("Two", 1, 1));
            listOfAs.add(new A("Ten", 3, 7));
            listOfAs.add(new A("Five", 3, 2));
            Collections.sort(listOfAs, new YourComparator());
            System.out.println(listOfAs);
        }
    }