Search code examples
androidsqlitecursor

How to use sqlite to retrieve single result?


I have this code that retrieves the last id

 public int retrieveLastId() {

            SQLiteDatabase db = this.getWritableDatabase();
            Cursor cursor = db.rawQuery("select "+ RECORDING_ID +" from " + DATABASE_TABLE + " ORDER BY "+ RECORDING_ID +" DESC LIMIT 1 ", null);


            int last = 0;
            last = Integer.parseInt(cursor.getString(0));
            Log.e("sfsdlkfjs dfl sd",cursor.getString(0));
            return  last;
        } 

but I get an error android.database.cursorindexoutofboundsexception how do I return the last id properly?


Solution

  • This cause of error is you do not check cursor is null .

    if (cursor.moveToFirst()) // Check your cursor has value?
       System.out.println(cursor.getString(0); 
    
    cursor.close();    //you should realse cursor