Search code examples
androidandroid-listviewandroid-cursorloaderandroid-loader

Sort ListView Using LoaderCallbacks<Cursor> by date


I am trying to create a Listview using LoaderCallbacks I am able to see all elements in the list. However now I want to sort it so the latest item in the DB is the first one on top. I have a Coulmn in the db called COLUMN_MESSAGE_DATE which contains a timestamp where I want the latest row to be on top.In the onCreateLoader when I return the loader I sort by this Coulmn but still the latest row is still on the bottom.... Am I missing something?

   public class MessageListFragment extends Fragment implements LoaderCallbacks<Cursor>{
@Override
public Loader<Cursor> onCreateLoader(int id, Bundle args)
{
    // Create the Cursor that will take care of the data being displayed

    Log.d("TAG", "onCreateLoader...");
    return new CursorLoader(getActivity(),CONTENT_URI, null, null, null,DataBase.COLUMN_MESSAGE_DATE);//I thought this should sort the list by date...
}

@Override
public void onLoadFinished(Loader<Cursor> arg0, Cursor cursor)
{
    // Now Bind the data to the View
    Log.d("TAG", "onLoadFinished...ARG1= " + cursor);
    mCusrorAdapter = new CustomCursorAdapter(getActivity(), cursor);
    mListView.setAdapter(mCusrorAdapter);

}

}


Solution

  • Although I cannot be sure without seeing your data, a timestamp is usually an incrementing value. That is, a current timestamp has a greater value than an older one. The default sort order is ASCending. Here I believe you want DESCending:

    return new CursorLoader(getActivity(),CONTENT_URI, null, null, null,DataBase.COLUMN_MESSAGE_DATE + " DESC");