我正在使用Realm gradle版本“3.0.0”,我有两个表“Word”和“收藏夹”如下
现在我要添加名为“History”的第三个表
因为我已经完成了以下代码
@Override
public void migrate(DynamicRealm realm, long oldVersion, long newVersion) {
final RealmSchema schema = realm.getSchema();
if (oldVersion == 0) {
RealmObjectSchema wordSchema = schema.get("Word");
wordSchema.addField(DBHelper.COLUMN_NAME_PRONOUCE, String.class);
wordSchema.addField(DBHelper.COLUMN_NAME_TYPE, String.class);
oldVersion++;
} if(oldVersion == 1){
RealmObjectSchema favouriteSchema = schema.get("Favourite");
favouriteSchema.addField(DBHelper.COLUMN_NAME_ID, String.class);
favouriteSchema.addField(DBHelper.COLUMN_NAME_WORD, String.class);
favouriteSchema.addField(DBHelper.COLUMN_NAME_OBJECT_ID, String.class);
favouriteSchema.addField(DBHelper.COLUMN_NAME_PRONOUCE, String.class);
favouriteSchema.addField(DBHelper.COLUMN_NAME_TYPE, String.class);
favouriteSchema.addField(DBHelper.COLUMN_NAME_MEANING, String.class);
oldVersion++;
}
if(oldVersion == 2){
schema.create("History")
.addField(DBHelper.COLUMN_NAME_ID, String.class)
.addField(DBHelper.COLUMN_NAME_WORD, String.class)
.addField(DBHelper.COLUMN_NAME_OBJECT_ID, String.class)
.addField(DBHelper.COLUMN_NAME_PRONOUCE, String.class)
.addField(DBHelper.COLUMN_NAME_TYPE, String.class)
.addField(DBHelper.COLUMN_NAME_MEANING, String.class);
oldVersion++;
}
}
但是我得到了错误,
io.realm.exceptions.RealmMigrationNeededException: Migration is required due to the following errors:
- Property 'History.id' has been changed from 'string' to 'int'.
- Property 'History.word' has been made required.
- Property 'History.objectId' has been made required.
- Property 'History.pronunciation' has been made required.
- Property 'History.type' has been made required.
- Property 'History.meaning' has been made required.
我之前没有创建任何历史记录表,而不是为什么说History.id已从'string'更改为'int'?
如何正确添加历史表?
if(oldVersion == 2){
schema.create("History")
.addField(DBHelper.COLUMN_NAME_ID, int.class)
.addField(DBHelper.COLUMN_NAME_WORD, String.class, FieldAttribute.REQUIRED)
.addField(DBHelper.COLUMN_NAME_OBJECT_ID, String.class, FieldAttribute.REQUIRED)
.addField(DBHelper.COLUMN_NAME_PRONOUCE, String.class, FieldAttribute.REQUIRED)
.addField(DBHelper.COLUMN_NAME_TYPE, String.class, FieldAttribute.REQUIRED)
.addField(DBHelper.COLUMN_NAME_MEANING, String.class, FieldAttribute.REQUIRED);
oldVersion++;
}
在您的测试手机上,之后只需卸载/重新安装应用程序,或者您需要修改架构版本并将字段更改为正确的类型。