RealmConfiguration config = new RealmConfiguration.Builder() .schemaVersion(2) .migration(new MyMigration()) .build();
其中,MyMigration是自己实现的 Migration 对象。
public class MyMigration implements RealmMigration {
@Override
public void migrate(DynamicRealm realm, long oldVersion, long newVersion) {
// 迁移逻辑
RealmSchema schema = realm.getSchema();
if (oldVersion == 0) {
// 迁移旧版本
schema.get("Person")
.addField("phone", String.class);
oldVersion++;
}
}
}
implementation 'io.realm:realm-gradle-plugin:10.8.0' annotationProcessor 'io.realm:realm-annotations:10.8.0' implementation 'io.realm:realm-kotlin-extensions:10.8.0'
RealmConfiguration config = new RealmConfiguration.Builder() .schemaVersion(2) .migration(new MyMigration()) .build(); Realm.setDefaultConfiguration(config);
这样,在执行数据库读写操作的时候,就可以不再出现io.realm.exceptions.RealmMigrationNeededException异常了。