Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set default value after adding a new field to Realm?

I have added a new field (lastUpdate) to an Object stored in 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; 
}

I have added it to 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++;
    }
}

Now when I am trying to access it via getLastUpdate() I get

java.lang.NullPointerException: Attempt to invoke virtual method 'long java.lang.Long.longValue()' on a null object reference

How do I properly set the default value?

like image 898
c0dehunter Avatar asked Dec 19 '22 02:12

c0dehunter


1 Answers

If you have pre-existing objects, then you need to update them in the transform.

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++;
}
like image 163
EpicPandaForce Avatar answered Dec 29 '22 12:12

EpicPandaForce