Skip to content Skip to sidebar Skip to footer

Android / Java: How To Get Last Row Value In Sqlite?

Hello I am using a sqlite database in my android application, and I have question: I am trying to get the last value text(thats the collumn) from the last row from the table TABLE_

Solution 1:

you are closing cursor before getting it's value

try this :

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

Solution 2:

From the android documentation: http://developer.android.com/reference/android/database/Cursor.html

abstract void close() Closes the Cursor, releasing all of its resources and making it completely invalid.

You are closing the cursor before returningthe string.

Solution 3:

Like @whatever5599451 said you should not close the cursor before you get value. Also try a query like this:

StringselectQuery="SELECT column FROM " + TABLE_XYZ + 
                     " ORDER BY column DESC LIMIT 1";

You can specify the columns also specify to return only 1 row.

This will bring back only the column you are ordering by you can also specify more columns example:

StringselectQuery="SELECT column, column2, column3 FROM " + TABLE_XYZ + 
                     " ORDER BY column DESC LIMIT 1";

* means select all columns

Solution 4:

to get the last column, use the name of the column instead of " * " (* means all, all the fields)

Solution 5:

@Steve: do this:

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

then you get just one String with the last record containing just the right column

Post a Comment for "Android / Java: How To Get Last Row Value In Sqlite?"