Why I'm getting an error after deleting a single row from an android sqlite table

After deleting a row from my sqlite database I get always an error if i browse the previous rows and come across the deleted row. it seems that the data is deleted however the _id still existing. here's my code:

this.database = openHelper.getWritableDatabase();
    String table = "flash_table";
    String whereClause = "Chap_ID=? AND Flash_Chap_Rank =?" ;
    String whereArgs[] = new String[] {""+cid, ""+fid};
    database.delete(table, whereClause, whereArgs);
    database.execSQL("UPDATE SQLITE_SEQUENCE SET seq = (SELECT MAX('Flash_ID')-1)  WHERE name = 'flash_table';");

here's the error message:

E/AndroidRuntime: FATAL EXCEPTION: main
              Process: com.newapp.flash, PID: 2579
              android.database.CursorIndexOutOfBoundsException: Index 0 requested, with a size of 0
                  at android.database.AbstractCursor.checkPosition(AbstractCursor.java:460)
                  at android.database.AbstractWindowedCursor.checkPosition(AbstractWindowedCursor.java:151)
                  at android.database.AbstractWindowedCursor.getString(AbstractWindowedCursor.java:65)

Can anyone help to overcome this issue.

1 answer

  • answered 2018-11-07 19:20 MikeT

    You are trying to read a row from a Cursor when there are no rows in the Cursor (you have very likely deleted the single row and hence there are no rows in the table to extract).

    The typical cause of this is when the useless check for the Cursor being null is made e.g.

    if (cursor != null) { 
        cursor.moveToFirst(); 
        cursor.getString(0); //<<<<<<<<< FAIL if cursor is empty
    }
    

    This will result in the failure above if there are no rows in the cursor.

    This is because a Cursor returned from an SQLiteDatabase method (e.g. query or rawQuery) will never be null. A valid Cursor would be returned.

    The moveToFirst method, doesn't fail, instead it returns false if the move could not be accomplished leaving the Cursor at a position of before the first row.

    So when you try to get data from the Cursor the exception saying that there are no rows (size is 0) for you to get the data from the column at offset 0.

    The fix is to check the return from the moveToFirst. e.g. (instead of the above code)

    if (cursor.moveToFirst()) {
        cursor.getString(0);
    }
    
    • Note this is the typical code that fails, there are other ways but basically any of the Cursor moveTo????? methods should be checked for the returned value. The Cursor getCount() method can also be used to check if there are any rows in the Cursor.