【问题标题】:Room database migration issue with column type Boolean列类型布尔的房间数据库迁移问题
【发布时间】:2020-02-24 13:50:03
【问题描述】:

我已经在我的应用程序中用几个表实现了 Room 数据库。现在我必须在我的数据库中添加另一个表,因为需求已经更新。我面临的问题是,当我执行具有列类型布尔应用程序崩溃的代码时。 我的实体类模型如下

@Entity(tableName = Constants.TABLE_NAME_CONVERSATION)
public class ConversationModel {

@PrimaryKey(autoGenerate = true)
private int id;

String inputWord, translatedWord,origin,targetLangCode;
boolean isSpeaking;


public ConversationModel() {
}
}

我写的迁移代码是:

 private static final Migration MIGRATION_1_2 = new Migration(1, 2) {
    @Override
    public void migrate(SupportSQLiteDatabase database) {

        String createTable = "CREATE TABLE IF NOT EXISTS 'conversation' (id  INTEGER NOT NULL PRIMARY KEY, inputWord TEXT, translatedWord TEXT, origin TEXT, targetLangCode TEXT, isSpeaking BOOLEAN)";

        database.execSQL(createTable);
    }
};

我收到的崩溃日志是这样的:

 Caused by: java.lang.IllegalStateException: Migration didn't properly handle conversation(com.translateall.language.free.translator.dictionary.speechtext.learnenglish.models.ConversationModel).
 Expected:
TableInfo{name='conversation', columns={isSpeaking=Column{name='isSpeaking',type='INTEGER', affinity='3', notNull=true, primaryKeyPosition=0}}, foreignKeys=[], indices=[]}
 Found:
 2019-10-29 13:24:31.433 20525-20525/com.translateall.language.free.translator.dictionary.speechtext.learnenglish E/AndroidRuntime:TableInfo{name='conversation', columns={
  isSpeaking=Column{name='isSpeaking', type='BOOLEAN', affinity='1', notNull=false, primaryKeyPosition=0}}, foreignKeys=[], indices=[]}

我的模型类有布尔类型的项目。为什么它需要整数类型?

【问题讨论】:

    标签: android database-migration android-room illegalstateexception


    【解决方案1】:

    ROOM 仅允许 TEXT、INTEGER、REAL 或 BLOB 列类型。

    您需要使用isSpeaking INTEGER。这将适用于boolean isSpeaking;

    所以你应该使用:-

    String createTable = "CREATE TABLE IF NOT EXISTS 'conversation' (id  INTEGER NOT NULL PRIMARY KEY, inputWord TEXT, translatedWord TEXT, origin TEXT, targetLangCode TEXT, isSpeaking INTEGER)";
    

    附:获得正确 SQL 的一种方法是在更改实体后进行编译,然后查看为数据库类(其中 ???? 是类)生成的 ??????_impl java SQL 将在 createAllTables 方法中。

    【讨论】:

    • 是的,我只是将其类型更改为值为 0 和 1 的整数。但我不知道 Room 不支持布尔类型。感谢您的建议。
    • @Raza SQLite 实际上也不支持 BOOLEAN,它被转换为 NUMERIC 类型关联see Datatypes In SQLite Version 3。然而,ROOM 对列类型非常具体(除其他外)。
    猜你喜欢
    • 2018-06-24
    • 2019-02-13
    • 2021-08-13
    • 2019-07-23
    • 2021-09-02
    • 2020-03-05
    • 1970-01-01
    • 1970-01-01
    • 2019-02-12
    相关资源
    最近更新 更多