无法迁移到 Room

Could not migrate to Room

我决定在我当前的应用程序中使用 Room。 发现当前架构中的一列没有类型,Room 在迁移时产生 IllegalStateException

java.lang.IllegalStateException: Migration didn't properly handle item.
 Expected:
TableInfo{name='item', columns={optional_modifiers=Column{a_type=Column{name='a_type', type='BLOB', notNull=false, primaryKeyPosition=0}...}
 Found:
TableInfo{name='item', columns={optional_modifiers=Column{a_type=Column{name='a_type', type='', notNull=false, primaryKeyPosition=0}...}

Sql table 创建脚本:

"create table item ("
                " id text primary key," +
                " a_type, "
//...
                ")

实体class:

@Entity(tableName = "item")
data class Item(
    @PrimaryKey
    val id: String?,
    val a_type: String? // actually I used several types, but none of them is worked
)

有什么办法可以解决这个问题吗?

修改你的class注解@Entity如下。

@Entity(tableName = "item")
data class Item(
   @PrimaryKey
   val id: String?,
   @ColumnInfo(typeAffinity = ColumnInfo.BLOB)
   val a_type: String?
   )

这会起作用,因为从错误中可以看出您的旧数据库模式具有名称='a_type'、类型='BLOB',因此您需要添加@ColumnInfo(typeAffinity = ColumnInfo.BLOB) 这将指示空间将 "a_type" 的数据类型视为 BLOB。

最近我注意到@ColumnInfo 还提供了 "UNDEFINED" 作为类型亲和力,因此您现在可以声明没有任何类型的 table 字段。Documentation

请尝试在您的项目中进行更新更改。

@Entity(tableName = "item")
data class Item(
@PrimaryKey
val id: String?,
@ColumnInfo(typeAffinity = ColumnInfo.UNDEFINED)
val a_type: String?
)

Sqlite 不允许编辑架构。所以唯一可能的方法是使用正确的列信息创建新的 table,将数据移动到它,删除旧的 table.

这是我使用的代码示例

        database?.execSQL("create table table_name_tmp ( " +
            " id text not null primary key"
            ")")
        database?.execSQL("""
            insert into table_name_tmp (id)

            select id
            from table_name
            """)
        database?.execSQL("drop table table_name")
        database?.execSQL("alter table table_name_tmp rename to table_name")