javaandroidsqlite

Android / Java: How to get last row value in sqlite?


I am using a sqlite database in my Android application, and I have question:

I am trying to get the last value text (that's the column) from the last row from the table TABLE_XYZ, but it does not work. I am using the following code - what am I doing wrong?

Another question is, how can I return two values instead of only one, when I want to get several values from the last row like column text and message?

private static final String KEY_MESSAGE = "message";
private static final String KEY_TEXT = "text";

...

String selectQuery= "SELECT * FROM " + TABLE_XYZ+" ORDER BY column DESC LIMIT 1";

SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
cursor.close();

return cursor.getString( cursor.getColumnIndex(KEY_TEXT) ); 

EDIT:

I made some errors in my query, which I fixed, but I still have errors:

    String selectQuery= "SELECT * FROM " + TABLE_XYZ +  " ORDER BY " +  KEY_TEXT+ " DESC LIMIT 1";
    SQLiteDatabase db = this.getReadableDatabase();
    Cursor cursor = db.rawQuery(selectQuery, null);
    String str =  cursor.getString( cursor.getColumnIndex(KEY_TEXT );
    cursor.close();
    return str; 

While debugging I can see that cursor does have the right values inside, but when I try to get the column value with this command

cursor.getString( cursor.getColumnIndex(KEY_TEXT );

it does not work...


Solution

  • you are closing cursor before getting it's value

    try this :

    String selectQuery= "SELECT * FROM " + TABLE_XYZ+" ORDER BY column DESC LIMIT 1";
    SQLiteDatabase db = this.getWritableDatabase();
    Cursor cursor = db.rawQuery(selectQuery, null);
    String str = "";
    if(cursor.moveToFirst())
        str  =  cursor.getString( cursor.getColumnIndex(KEY_TEXT) );
    cursor.close();
    return str;