房间迁移未正确处理

时间:2018-11-21 08:46:36

标签: android android-room

得到以下异常:

预期:

  

TableInfo {name ='chat_table',columns = {message = Column {name ='message',   type ='TEXT',affinity ='2',notNull = false,primaryKeyPosition = 0},   messageStatus = Column {name ='messageStatus',type ='TEXT',affinity ='2',   notNull = false,primaryKeyPosition = 0},id = Column {name ='id',   type ='INTEGER',affinity ='3',notNull = true,primaryKeyPosition = 1}},   foreignKeys = [],索引= []}

发现:

  

TableInfo {name ='chat_table',   column = {messageStatus = Column {name ='messageStatus',type ='TEXT',   finity ='2',notNull = false,primaryKeyPosition = 0},   id = Column {name ='id',type ='INTEGER',affinity ='3',notNull = false,   primaryKeyPosition = 1},message = Column {name ='message',type ='TEXT',   finity ='2',notNull = false,primaryKeyPosition = 0}},foreignKeys = [],   index = []}

任何人都可以提出这里的问题吗?我只是将表列值复制到另一个表。然后删除第一个表,然后将新表重命名为旧名称。

 1. database.execSQL("CREATE TABLE chat_table_new (id INTEGER,
        messageStatus TEXT, message TEXT, PRIMARY KEY(id))")
 2. database.execSQL("INSERT INTO chat_table_new SELECT * FROM
        chat_table") 
 3. database.execSQL("DROP TABLE chat_table") 
 4. database.execSQL("ALTER TABLE chat_table_new RENAME TO chat_table")

1 个答案:

答案 0 :(得分:0)

尝试这种方式。

@Database(entities = {Student.class, BookIssue.class},version = 1)
public abstract class StudentDatabase extends RoomDatabase {
private static StudentDatabase studentDatabase;
public static StudentDatabase getStudentDatabase(Context context)
{
    if (studentDatabase==null)
    {
        studentDatabase= Room.databaseBuilder(context.getApplicationContext(),StudentDatabase.class,"student-database").addMigrations(StudentDatabase.MIGRATION_1_2).build();

    }

    return studentDatabase;
}

public abstract StudentDao studentDao();
public abstract BookDao bookDao();

public static final Migration MIGRATION_1_2 =new Migration(1,2) {
    @Override
    public void migrate(SupportSQLiteDatabase database) {
        database.execSQL("alter table Student "+"add column pf String");
    }
};
}

更多理解请参考此链接 https://medium.com/androiddevelopers/understanding-migrations-with-room-f01e04b07929