You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Android Kotlin开发报错:CursorWindow读取失败问题求助

错误排查与解决

核心问题定位

出现java.lang.IllegalStateException: Couldn't read row 0, col -1的原因如下:

  • SQL语法错误:SELECT *FROM $TABLE_NAME中*和FROM之间缺少空格,导致SQL解析失败,返回的Cursor结构异常。
  • 列名误用:cursor.getColumnIndex(TABLE_NAME)传入的是表名而非对应列名,getColumnIndex找不到列时返回-1,读取该索引的列会触发异常。
  • 错误的异常处理:db.execSQL(selectQuery)不能执行查询语句,execSQL仅支持增删改操作,这段逻辑完全无效。

修复后的代码

@SuppressLint("Range")
fun getAllTask(): ArrayList<TaskListModel> {
    val taskListModel = ArrayList<TaskListModel>()
    val db = this.readableDatabase
    // 修复SQL语句的空格问题
    val selectQuery = "SELECT * FROM $TABLE_NAME"

    // 使用use函数自动管理Cursor生命周期,避免手动关闭遗漏
    db.rawQuery(selectQuery, null).use { cursor ->
        if (cursor.moveToFirst()) {
            do {
                val task = TaskListModel()
                // 直接用getInt读取整数类型,避免字符串转整数的异常
                task.id = cursor.getInt(cursor.getColumnIndex(ID))
                // 替换TABLE_NAME为实际的名字列常量(比如NAME,需和表结构一致)
                task.name = cursor.getString(cursor.getColumnIndex(NAME))
                task.details = cursor.getString(cursor.getColumnIndex(TASK_DETAILS))
                taskListModel.add(task)
            } while (cursor.moveToNext())
        }
    }
    return taskListModel
}

额外注意事项

  • 确保ID、NAME、TASK_DETAILS常量的字符串值和数据库表的实际列名完全一致(SQLite默认大小写不敏感,但建议严格匹配避免隐患)。
  • 读取整数类型字段时,优先使用cursor.getInt()而非字符串转换,更高效且避免类型转换异常。
  • 用Cursor.use{}替代手动cursor.close(),能自动处理资源释放,防止内存泄漏。

内容的提问来源于stack exchange,提问作者Ankit Vora

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.08 01:20:37