Search code examples
androidandroid-studiokotlinandroid-sqlitesqliteopenhelper

i'm getting error whenEver i try to get data from my db using this function(i'm using kotlin with android studio)


fun readChore(id:Int):Chore{
     val db:SQLiteDatabase=writableDatabase

    val cursor:Cursor=db.query(TABLE_NAME,arrayOf(KEY_ID,KEY_CHORE_ASSIGNED_TO, KEY_CHORE_ASSIGNED_BY,
               KEY_CHORE_ASSINED_TIME),KEY_ID+"=?",arrayOf(id.toString()),
               null,null,null,null)

    Log.d("position",cursor.position.toString())

    cursor.moveToFirst()

    val chore=Chore(
            cursor.getString(cursor.getColumnIndex(KEY_CHORE_NAME)),
            cursor.getString(cursor.getColumnIndex(KEY_CHORE_ASSIGNED_TO)),
            cursor.getString(cursor.getColumnIndex(KEY_CHORE_ASSIGNED_BY)),
            cursor.getLong(cursor.getColumnIndex(KEY_CHORE_ASSINED_TIME))
    )

    return chore
}

But all i'm getting is an error__saying ..."Failed to read row 0, column -1 from a CursorWindow which has 1 rows, 4 columns."


Solution

  • You have to add KEY_CHORE_NAME to the selected rows

    val cursor:Cursor=db.query(TABLE_NAME,arrayOf(KEY_ID, KEY_CHORE_NAME ,KEY_CHORE_ASSIGNED_TO, KEY_CHORE_ASSIGNED_BY,
               KEY_CHORE_ASSINED_TIME),KEY_ID+"=?",arrayOf(id.toString()),
               null,null,null,null)
    

    For future debugging you can use Databaseutils.dumpCursor() to see the contents of your cursor, which is otherwise hard to see.

    Also don't forget to close the cursor cursor.close() before the return statement.