SQLiteException code 0 android data_error ai_generated true

android.database.sqlite.SQLiteException:无法从游标读取:列 'price' 的类型是 REAL,但期望的是 INTEGER(代码 0)

android.database.sqlite.SQLiteException: Cannot read from cursor: column 'price' has type REAL but expected INTEGER (code 0)

ID: android/sqlite-cursor-column-type-mismatch

其他格式: JSON · Markdown 中文 · English
92%修复率
88%置信度
1证据数
2023-11-20首次发现

版本兼容性

版本状态引入弃用备注
Android 11 (API 30) active
Android 12 (API 31) active
Android 13 (API 33) active

根因分析

游标尝试通过 getInt() 将 REAL 列读取为 INTEGER,导致 SQLite 动态类型系统中的类型不匹配。

English

Cursor attempts to read a REAL column as INTEGER via getInt(), causing type mismatch in SQLite's dynamic typing system.

generic

官方文档

https://developer.android.com/reference/android/database/sqlite/SQLiteException

解决方案

  1. Use `cursor.getDouble(cursor.getColumnIndexOrThrow("price"))` instead of getInt() to read REAL columns correctly.
  2. In Room, annotate the field as `Double` (not Int) in the entity class: `@ColumnInfo(name = "price") val price: Double`
  3. Use `cursor.getType(columnIndex)` to check the type before reading: if type == Cursor.FIELD_TYPE_FLOAT, use getDouble(); else getInt().

无效尝试

常见但无效的做法:

  1. Cast the column value to int in SQL query: `CAST(price AS INTEGER)` 70% 失败

    This truncates decimals, losing precision; the real fix is to read as getDouble().

  2. Change column type in CREATE TABLE to INTEGER 85% 失败

    SQLite is dynamically typed; the column type only affects affinity, not actual stored values. Existing data remains REAL.

  3. Use getString() and parse to int 90% 失败

    Parsing '12.99' to int throws NumberFormatException or truncates incorrectly.