在Realm上迁移0.81.1

时间:2015-07-06 15:13:17

标签: java android realm realm-migration

添加对象后得到了不同的异常。

  • 需要迁移
  • 在计划中找不到类
  • 磁盘上的
  • 版本比请求的版本新

有什么问题?

1 - MainActivity.java

RealmConfiguration realmConfiguration =
            new RealmConfiguration.Builder(context)
            .build();
    Realm.setDefaultConfiguration(realmConfiguration);

    Realm realm = Realm.getDefaultInstance();

    realm.executeTransaction(new Realm.Transaction() {
        @Override
        public void execute(Realm realm) {
            RealmTestObjectOne testObjectOne = new RealmTestObjectOne();
            testObjectOne.setValue(value);
            realm.copyToRealmOrUpdate(testObjectOne);
        }
    });

2 - RealmTestObjectOne.java

public class RealmTestObjectOne extends RealmObject {
    @PrimaryKey
    private int key = 1;

    private String value;

    public RealmTestObjectOne() {
   }

    public int getKey() {
        return key;
    }

    public void setKey(int key) {
        this.key = key;
    }

    public String getValue() {
        return value;
    }

    public void setValue(String value) {
        this.value = value;
    }
}

3 - 构建&运行

4 - 添加RealmTestObjectTwo.java 与RealmTestObjectOne.java相同但ID不同

5 - 修改RealmConfiguration

RealmConfiguration realmConfiguration =
    new RealmConfiguration.Builder(context)
    .schemaVersion(2)
    .migration(new Migration())
    .build();

5 - 添加Migration.java

public class Migration implements RealmMigration {
    @Override
    public long execute(Realm realm, long l) {
        l += 1;
        return l;
    }
}

解决

感谢@geisshirt回答。

public class Migration implements RealmMigration {
@Override
public long execute(Realm realm, long version) {
    if (version == 0) {
        Table table = realm.getTable(RealmTestObjectTwo.class);
        table.addColumn(ColumnType.INTEGER, "key");
        table.addColumn(ColumnType.STRING, "value");
        table.setPrimaryKey("key");
        version += 1;
    }

    return version;
}
}

0 个答案:

没有答案