添加对象后出现不同的异常。
- 需要迁移
- 在方案中找不到类
- 磁盘上的版本比请求的版本新
怎么了?
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 -添加迁移.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;
}
}