如何在向Realm添加新字段后设置默认值?

时间:2017-12-23 07:50:52

标签: android realm database-migration

我已将新字段(lastUpdate)添加到存储在Realm DB中的对象:

public class ChartObject extends RealmObject {
    ...
    private Long lastUpdate = 0L;

    public ChartObject() {
        ...
        lastUpdate = 0L;
    }

    ...
    public long getLastUpdate() { return lastUpdate; }
    public void setLastUpdate(long lastUpdate) { this.lastUpdate = lastUpdate; 
}

我已将其添加到MyMigration.java:

@Override
public void migrate(DynamicRealm realm, long oldVersion, long newVersion) {
    RealmSchema schema = realm.getSchema();

    if (oldVersion < 4) {
        schema.get("ChartObject")
                .addField("lastUpdate", Long.class); // how to set default value?
        oldVersion++;
    }
}

现在当我尝试通过getLastUpdate()访问它时,我得到了

  

java.lang.NullPointerException:尝试调用虚拟方法'long   关于空对象引用的java.lang.Long.longValue()'

如何正确设置默认值?

1 个答案:

答案 0 :(得分:6)

如果您有预先存在的对象,则需要在转换中更新它们。

if (oldVersion < 4) {
    schema.get("ChartObject")
            .addField("lastUpdate", Long.class);
    schema.get("ChartObject").transform(new RealmObjectSchema.Function() {
        @Override
        public void apply(DynamicRealmObject obj) {
           obj.setLong("lastUpdate", 0L);
        }
    });
    oldVersion++;
}