Android - How to sort a list

I have a list that I populate with data from a database, and now I want to sort this data by name and date.

I am still new to Android programming, so I can’t figure out how to do this, I hope someone can help.

Here's how to populate the list:

    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 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);
}
+3
source share
2 answers

The best way would be to sort the data as it gets from your database. This is done when creating the cursor (which is not part of the code you posted). When you query the database, you can specify the sort order.

+2
source

, , . Sort , , .

:

String sortStr = DBAdapter.KEY_TITLE + "asc, " + DBAdapter.KEY_DATE + " asc";

( , )

, order by .

, DBAdapter ( , getAllTitles method).

+1

Source: https://habr.com/ru/post/1771607/


All Articles