views:

72

answers:

2

I have a list that i fill with data from a database, and now i want to sort this data by title and date.

Im still new to programming for Android, so cant figure out how to do this here, hope someone can help.

Here is how the list is filled:

    public void fillData()
{
    // get all the data from database
    DBAdapter db = new DBAdapter(this);
    db.open();

    mCategoriesCursor = db.getAllTitles();
        startManagingCursor(mCategoriesCursor);

    String[] from = new String[] { DBAdapter.KEY_TITLE, DBAdapter.KEY_DATE };
    int[] to = new int[] { R.id.text1, R.id.text2 };

    // Now create an array adapter and set it to display using our row
    SimpleCursorAdapter categories =
        new SimpleCursorAdapter(this, R.layout.categories_row, mCategoriesCursor, from, to);
    setListAdapter(categories);

    db.close();
}    

Here is the sql:

    //---retrieves all the categories---
public Cursor getAllTitles() 
{
    return db.query(DATABASE_TABLE, new String[] {
            KEY_ROWID, 
            KEY_TITLE,
            KEY_DATE,
            KEY_EXTRA}, 
            null, 
            null, 
            null, 
            null, 
            null);
}
+1  A: 

The best way would be to sort the data as you get them from your database. That is done as you create the cursor (which is not part of the code you posted). When you query a database, you can specify the sort order.

EboMike
Yep, that worked fine. So i was looking in the wrong place hehe.This worked perfectly. What i did was change the last "null" in the query in "public Cursor getAllTitles() " to KEY_TITLE or KEY_DATA to sort.
A: 

You should probably do the sorting when you call the data from the database itself. To do this you'll want to populate the Sort parameter of whatever query method you're using to pull this data.

It should go something like this:

String sortStr = DBAdapter.KEY_TITLE + "asc, " + DBAdapter.KEY_DATE + " asc"; (this sort string you would put into the query method as the last parameter)]

If you're doing this as a raw query you'd append a full order by statement at the end of your query.

If you want further detail, you're going to have to show us the internal workings of your DBAdapter (specifically the getAllTitles method).

Marloke