goo*_*man 9 android realm realm-migration
因此,我们有一个用户拥有应用程序版本1.0的场景.版本2.0出来了,但用户没有更新.当3.0版本出来时,用户决定更新.
由于用户尚未更新应用程序,因此领域文件也未更新,因此在从1.0版迁移到3.0版时,version参数Migration.execute将具有值1而不是2.
当用户直接安装应用程序版本2.0然后迁移到3.0版时,也会出现问题.与前一种情况相同,version参数将是错误的.
有没有办法妥善处理这些案件?
实际上 Realm 的迁移示例就展示了这种场景。
public class Migration implements RealmMigration {
@Override
public long execute(Realm realm, long version) {
// Step 0
if (version == 0) {
//Do the migration from 0 to 1
version++;
}
// Step 1
// Now the version is at least 1
if (version == 1) {
// Do the migration from 1 to 2
version++;
}
// Step 2
if (version == 2) {
// Do the migration from 2 to 3
version++;
}
// Now you get your final version 3
return version;
}
}
Run Code Online (Sandbox Code Playgroud)
只需一步步编写迁移,然后一一运行它们,直到获得最新的架构版本。对于您的情况,用户可能在这里拥有 Realm db 版本 0,并且 step0 将首先运行。然后在步骤 0 块中版本变为 1,然后将运行步骤 1。
------------ 更新用户直接安装版本3案例 ------------
创建领域实例时,代码如下:
RealmConfiguration config = new RealmConfiguration.Builder(this)
.migration(migration)
.schemaVersion(3)
.build();
Realm realm = Realm.getInstance(config);
Run Code Online (Sandbox Code Playgroud)
请注意这里schemaVersion(3)。仅当需要迁移时才会RealmMigration.execute()执行。这意味着如果用户直接安装版本 3 而没有在设备上安装任何以前的版本,则不会调用 ,并且在 Realm 文件初始化后,架构版本将设置为 3。RealmMigration.execute()
我不是Realm大师,也没有Realm在实际项目中使用过,但这种方法应该有效:
假设您使用此迁移示例:
您需要在项目中保存一个附加属性(例如SharedPreferences)- latestMigrationVersion. 默认情况下,latestMigrationVersion = 0,这意味着我们尚未运行迁移。
Migration.java按以下方式修改您的类:
@Override
public long execute(Realm realm, long version) {
// check if the previous migration took place
if (version > 0 && version - 1 > latestMigrationVersion) {
// user missed migration
// then we need to run previous missed migrations before
version = latestMigrationVersion;
}
// do migrations as described in the example.
...
// update latestMigrationVersion for future checks
latestMigrationVersion = version;
// save the property locally
}
Run Code Online (Sandbox Code Playgroud)
现在,如果用户直接安装2.0版本,则在2.0 -> 3.0迁移之前将执行之前的所有迁移。
Unit tests应该帮助您检查所有可能的迁移:0.0 -> 3.0、1.0 -> 2.0、2.0 -> 3.0等。
| 归档时间: |
|
| 查看次数: |
1286 次 |
| 最近记录: |