这就是我要的:
public class CustomRealmMigration implements RealmMigration {
// Current version
private static final long SCHEMA_VERSION = 4;
private final Context mContext;
public CustomRealmMigration(Context context) {
mContext = context;
}
@Override
public long execute(Realm realm, long version) {
if (SCHEMA_VERSION < version) {
// Rollback, not allow
deleteRealm();
return SCHEMA_VERSION;
}
return version;
}
private void deleteRealm() {
RealmConfiguration realmConfiguration = new RealmConfiguration.Builder(mContext)
.name(Realm.DEFAULT_REALM_NAME)
.build();
Realm.deleteRealm(realmConfiguration);
}
}
错误:
Caused by: java.lang.IllegalStateException: It's not allowed to delete the file associated with an open Realm. Remember to close() all the instances of the Realm before deleting its file.
迁移时如何删除Realm?或者如何在其他地方获取旧版本的Realm?
最佳答案
如果您不想在架构更改时迁移数据,而只是重置/清除数据库,则可以执行以下操作:
RealmConfiguration realmConfiguration = new RealmConfiguration.Builder(mContext)
.name(Realm.DEFAULT_REALM_NAME)
.deleteRealmIfMigrationRequired()
.build();
这也意味着您不必提供任何迁移代码。