Search code examples
javaandroidsqldatabasecursor

Reading Sql Database from backward


Hey guy I have a question. How can I read my Sql datas from backward. I tried a lot of things I found in the net but nothing works here is my code:

public Cursor getAllRows() {
    String where = null;
    Cursor c =  db.query(true, DATABASE_TABLE, ALL_KEYS, 
                        where, null, null, null,null,null);
    if (c != null) {
        c.moveToFirst();
    }
    return c;

And the code for the Cursor:

Cursor cursor = myDb.getAllRows();

// Allow activity to manage lifetime of the cursor.
// DEPRECATED! Runs on the UI thread, OK for small/short queries.
startManagingCursor(cursor);

// Setup mapping from cursor to view fields:
String[] fromFieldNames = new String[] 
        {DBAdapter.KEY_KALO, DBAdapter.KEY_HYDRATE, DBAdapter.KEY_FAT, DBAdapter.KEY_PROTEIN ,DBAdapter.KEY_CAL};
int[] toViewIDs = new int[]
        {R.id.item_Kalorien,     R.id.item_KG_in_g,           R.id.item_F_in_g,     R.id.item_P_in_g,R.id.item_cal};

// Create adapter to may columns of the DB onto elemesnt in the UI.
SimpleCursorAdapter myCursorAdapter = 
        new SimpleCursorAdapter(
                this,       // Context
                R.layout.item_tagebuch, // Row layout template
                cursor,                 // cursor (set of DB records to map)
                fromFieldNames,         // DB Column names
                toViewIDs               // View IDs to put information in
                );

// Set the adapter for the list view
ListView myList = (ListView) findViewById(R.id.listView1);
myList.setAdapter(myCursorAdapter);

Tank you for helping, and sorry for my bad english:)


Solution

  • The statement "from backward" is ambiguous i am assuming you want to read db in a particular order

    if you want to read in descending order of a field say 'foo' then

    String ORDER = "foo DESC";/*use ASC for ascending order*/

    and Change the cod as follows

    public Cursor getAllRows() {
        String where = null;
        String Order = "foo DESC";
        Cursor c =  db.query(true, DATABASE_TABLE, ALL_KEYS, 
                            where, null, null, null,Order,null);
        if (c != null) {
            c.moveToFirst();
        }
        return c;
    

    Here is the syntax of query

    public Cursor query (String table, String[] columns, String selection,String[] selectionArgs, String groupBy, String having, String orderBy, String limit)

    Refer to the below link for further explanantion SQLiteDatabase Android