我是Realm的新手。我将领域用作本地数据库,如果应用程序更新,我不想丢失数据。我之前做的是
public static Realm getRealmInstanse(){
RealmConfiguration config = new RealmConfiguration
.Builder()
.deleteRealmIfMigrationNeeded()
.build();
try {
return Realm.getInstance(config);
} catch (RealmMigrationNeededException e){
try {
Realm.deleteRealm(config);
//Realm file has been deleted.
return Realm.getInstance(config);
} catch (Exception ex){
throw ex;
//No Realm file to remove.
}
}
}
现在我想我应该做以下事情:
public static Realm getRealmInstanse(){
RealmConfiguration config = new RealmConfiguration
.Builder()
.migration(new RealmMigration() {
@Override
public void migrate(DynamicRealm realm, long oldVersion, long newVersion) {
}
})
.build();
return Realm.getInstance(config);
}
为了复制数据,我应该在 migrate() 方法中做什么?那么架构呢,我应该使用架构版本以及出于什么目的?
改变模式的逻辑是什么?例如,如果出于某种原因我要更改数据库的结构,我可以只更改 migrate() 方法中的架构吗?
我找到了这个例子,但我实际上不知道它是在保存数据还是只是在更改架构
if (oldVersion == 0) {
RealmObjectSchema personSchema = schema.get("Person");
// Combine 'firstName' and 'lastName' in a new field called 'fullName'
personSchema
.addField("fullName", String.class, FieldAttribute.REQUIRED)
.transform(new RealmObjectSchema.Function() {
@Override
public void apply(DynamicRealmObject obj) {
obj.set("fullName", obj.getString("firstName") + " " + obj.getString("lastName"));
}
})
.removeField("firstName")
.removeField("lastName");
oldVersion++;
}