Sahil Lombar
Sahil Lombar

Reputation: 145

Android SQLITE Query: Getting last 3 entries

I am trying to get the last 3 entries made to the database. Im using the following code but im only getting the last entry not the last 3.

 String query = "Select * from " + TABLE_DETAILS + " DESC limit 3;";

     SQLiteDatabase db = this.getWritableDatabase();

     Cursor cursor  = db.rawQuery(query, null);

    if (cursor.moveToFirst()) {
        cursor.moveToFirst();
        System.out.println(Integer.parseInt(cursor.getString(2)));
        cursor.close();
    } else {
    }
    db.close();

Thanks

Upvotes: 0

Views: 334

Answers (1)

laalto
laalto

Reputation: 152867

You'll need to loop with the cursor to get all result rows, e.g. instead of

if (cursor.moveToFirst()) {
   ...

loop like this

while (cursor.moveToNext()) {
  System.out.println(cursor.getString(2));
}
cursor.close();

To change the ordering, add ORDER BY <expression> to your query, for example

SELECT ... ORDER BY _id DESC LIMIT 3

Upvotes: 4

Related Questions