每当我尝试使用此功能从我的数据库获取数据时,我都会收到错误消息(我将 kotlin 与 android studio 一起使用)

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
}

但我得到的只是 error__saying ..."Failed to read row 0, column -1 from a CursorWindow which has 1 rows, 4 columns."

您必须将 KEY_CHORE_NAME 添加到所选行

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)

为了将来的调试,您可以使用 Databaseutils.dumpCursor() 查看光标的内容,否则很难看到。

另外不要忘记在 return 语句之前关闭游标 cursor.close()