Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to sort the CursorLoader results?

I use CursorLoader to query a result, which is not the order that I want to show in the ListFramgenet. How to sort it ?

I use this to set the adapter:

    mAdapter = new SimpleCursorAdapter(getActivity(),
            android.R.layout.simple_list_item_2, null,
            new String[] { "name", "distance"},
            new int[] { android.R.id.text1, android.R.id.text2 }, 0);
    setListAdapter(mAdapter);

    // Start out with a progress indicator.
    setListShown(false);

    // Prepare the loader.  Either re-connect with an existing one,
    // or start a new one.
    getLoaderManager().initLoader(0, null,  this);

Create loader :

public Loader<Cursor> onCreateLoader(int id, Bundle args) {

    return new CursorLoader(getActivity(), 
            Uri.withAppendedPath(TraceTable.CONTENT_URI, "latest"),
            MEMBERS_PROJECTION,
            null,
            null,
            null);        

}


public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
    mAdapter.changeCursor(data);

    // The list should now be shown.
    if (isResumed()) {
        setListShown(true);
    } else {
        setListShownNoAnimation(true);
    }
}

Well, there are latitude and longitude the queried results. I want to calculate the distance between my location and these results. and sort by distance asc.

How to sort it? Any answer will be appricated

like image 282
Alex Chan Avatar asked Dec 19 '13 16:12

Alex Chan


1 Answers

It's actually quite easy:

from this:

new CursorLoader(getActivity(), 
        Uri.withAppendedPath(TraceTable.CONTENT_URI, "latest"),
        MEMBERS_PROJECTION,
        null,
        null,
        null);

to this:

// You could have them calculated in the projection like this:
String[] projection = { COLUMN1 + " * " + COLUMN2 + " as data", // Whatever your calculations are
COLUMN1, COLUMN2, COLUMN3, etc..  };
new CursorLoader(getActivity(), 
        Uri.withAppendedPath(TraceTable.CONTENT_URI, "latest"),
        projection, 
        null,
        null,
        "data ASC");

Remember that if you have some method in your provider that does a check to the projection and rise an exception, you would have to comment it out for the moment you are doing the test or add the new column (the one you do the calculation with) to your official projection array.

like image 80
cass Avatar answered Sep 30 '22 17:09

cass