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

Room数据库迁移时如何通过SQL添加Bitmap字段?

解决Room迁移中添加Bitmap字段的错误

问题根源

SQLite本身没有BITMAP数据类型,你通过TypeConverter将Bitmap转换为ByteArray存储,对应SQLite的BLOB类型,所以迁移SQL里用BITMAP会直接触发错误。

正确解决方案

  1. 修正迁移SQL的字段类型
    把迁移语句里的BITMAP换成SQLite支持的BLOB,同时因为原有数据没有这个字段,必须设置为允许空值(NULL),否则迁移会失败:

    val MIGRATION_1_2 = object : Migration(1, 2) {
        override fun migrate(database: SupportSQLiteDatabase) {
            database.execSQL(
                "ALTER TABLE person_table ADD COLUMN profilePicture BLOB NULL"
            )
        }
    }
    
  2. 调整数据模型的可空性
    现有数据库记录没有profilePicture值,所以模型里的该字段需要设为可空类型,避免Room读取数据时抛出空指针异常:

    @Entity(tableName = "person_table")
    data class PersonModel(
        @PrimaryKey(autoGenerate = true)
        val id: Int,
        val name: String,
        val surname: String,
        val profilePicture: Bitmap? // 修改为可空类型
    )
    
  3. 确认TypeConverter生效
    你的Converter类实现是正确的,确保@TypeConverters(Converter::class)注解已经加在PersonDatabase类上,Room会自动处理Bitmap和ByteArray的双向转换。

额外说明

如果需要给现有数据设置默认占位图,可以在迁移后执行UPDATE语句填充默认值,示例:

override fun migrate(database: SupportSQLiteDatabase) {
    database.execSQL("ALTER TABLE person_table ADD COLUMN profilePicture BLOB NULL")
    // 替换defaultBitmapBytes为你实际的默认Bitmap字节数组
    database.execSQL("UPDATE person_table SET profilePicture = ? WHERE profilePicture IS NULL", arrayOf(defaultBitmapBytes))
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.18 03:01:22