I am populating my ListView from a Database according to the code shown below in a Fragment which implements CursorLoader. Earlier I was using SimpleCursorAdapter for the same purpose but I had to change to ArrayAdapter for some reasons.
The Database have only two columns:
_id(integer primary key autoincrement) and message(string not null)
The ListView is working fine but the problem is that the strings shown in the listview are automatically sorted alphabetically and not in the order they were stored. Whereas I did not face this problem while using SimpleCursorAdapter.
Could anyone please tell what I'm doing wrong this time and how to correct it.
@Override
public Loader<Cursor> onCreateLoader(int arg0, Bundle arg1) {
String[] projection = {KEY_ROWID, KEY_MESSAGE};
CursorLoader cursorLoader = new CursorLoader(getActivity(),
CONTENT_URI, projection, null, null, null);
return cursorLoader;
}
@Override
public void onLoadFinished(Loader<Cursor> loader, Cursor cursor) {
if(cursor != null){
msgList = new ArrayList<String>();
cursor.moveToFirst();
while(cursor.isAfterLast() == false){
msgList.add(cursor.getString(1).toString());
cursor.moveToNext();
}
}
mAdapter = new ArrayAdapter<String>(getActivity(), R.layout.msg_list, R.id.list_textView, msgList);
listview.setAdapter(mAdapter);
}
@Override
public void onLoaderReset(Loader<Cursor> arg0) {
if (mAdapter != null)
listview.setAdapter(null);
}
Thanks
The data from a DB is always fetched in an unpredictable order.
You have to specify the column/s against which you want the data to be sorted and the order direction for each column (default: ASC).
Try using CursorLoader(..., KEY_ROWID + " DESC")