I've searched for solutions for a long time and still can't find a relevant way to make it work.
I have this method inside an external myDBClass.java in Android studio to find last inserted row.
public Cursor lastrow() {
// TODO Auto-generated method stub
try{
SQLiteDatabase db;
db = this.getReadableDatabase(); // Read Data
String query = "SELECT ID As _id, Spinpos, Details, Setfor from alarm order by ID DESC limit 1";
Cursor cursor = db.rawQuery(query, null);
if(cursor != null)
{
cursor.moveToFirst();
return cursor;
}
else
{
return null;
}
} catch (Exception e) {
return null;
}
}
Then I execute it in MainActivity.java
myDBClass myDb = new myDBClass(this);
Cursor cursor = myDb.lastrow();
String SongID = cursor.getString(cursor.getColumnIndex("Spinpos"));
Toast.makeText(this,SongID,Toast.LENGTH_LONG).show();
It throws android.database.CursorIndexOutOfBoundsException. Please provide me a solution.
Cursor is initialized to position -1, so when you call moveToNext() will return true if the cursor reach position 0, that mean the db fetched at least one value.
Use this
if(cursor.moveToNext()){
//database fetched at least one value
}