簡體   English   中英

Android Room遷移未正確處理

[英]Android Room migrations did not properly handled

我已經編寫了Android Room遷移文件,但是由於某種原因它無法正確處理。

這是錯誤:

    Expected:
TableInfo{name='Likes', columns={creatorId=Column{name='creatorId', type='TEXT', notNull=false, primaryKeyPosition=0}, messageId=Column{name='messageId', type='TEXT', notNull=false, primaryKeyPosition=0}, createdAt=Column{name='createdAt', type='TEXT', notNull=false, primaryKeyPosition=0}, id=Column{name='id', type='TEXT', notNull=false, primaryKeyPosition=0}, dbId=Column{name='dbId', type='INTEGER', notNull=true, primaryKeyPosition=1}, timestamp=Column{name='timestamp', type='TEXT', notNull=false, primaryKeyPosition=0}}, foreignKeys=[], indices=[]}
 Found:
TableInfo{name='Likes', columns={dbId=Column{name='dbId', type='INTEGER', notNull=true, primaryKeyPosition=1}, creatorId=Column{name='creatorId', type='TEXT', notNull=false, primaryKeyPosition=0}, messageId=Column{name='messageId', type='TEXT', notNull=false, primaryKeyPosition=0}, id=Column{name='id', type='TEXT', notNull=false, primaryKeyPosition=0}, timestamp=Column{name='timestamp', type='TEXT', notNull=false, primaryKeyPosition=0}}, foreignKeys=[], indices=[]}

這是遷移腳本:

database.execSQL("CREATE TABLE Likes (id TEXT, creatorId TEXT, messageId TEXT,"
                       + " timestamp TEXT, dbId INTEGER NOT NULL, PRIMARY KEY(dbId))");

這是模型類:

@Entity(tableName = "Likes")
public class LikeDbModel {

@PrimaryKey private int dbId;
private String id;
private String creatorId;
private String messageId;
private String timestamp;
private String createdAt;

public LikeDbModel() {
}
}

有人可以幫忙嗎?

它在遷移中缺少createdAt字段

似乎您正在嘗試添加一列createdAt。 創建數據庫時,我認為您已經完成了在數據庫創建中添加.addMigrations(MIGRATION_1_2)行。

INSTANCE = Room.databaseBuilder(context.getApplicationContext(),
                        YourDatabase.class, "your_database.db")
                        .addMigrations(
                                MIGRATION_1_2
                        )
                        .build();

然后,首先刪除表,然后創建表或使用alter table語句,以正確實施遷移。

    static final Migration MIGRATION_1_2 = new Migration(1, 2) {
    @Override
    public void migrate(SupportSQLiteDatabase db) {
           //Either
           db.execSQL("drop table Likes"); //if existing table
           db.execSQL("CREATE TABLE Likes (id TEXT, creatorId TEXT, messageId TEXT,"
                   + " timestamp TEXT, createdAt TEXT, dbId INTEGER NOT NULL, PRIMARY KEY(dbId))")

            //or
            db.execSQL("alter table add createdAt TEXT");

    }
};

您收到的錯誤是因為房間正在將您的實體與數據庫中的現有表進行比較。 您也可以將遷移語句包裝在try / catch SQLiteException中,以查看有效的方法。

如果您不想丟失表中的數據,請改用alter表。 如果要刪除/創建,請確保首先使用新結構將數據復制到新表,將數據復制到新表,刪除原始的Likes表,然后將新表重命名為Likes。 在這里查看示例

會議室文檔: https : //developer.android.com/training/data-storage/room/migrating-db-versions

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM