Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Realm on android im getting "Field already exists" error but its on a fresh install?

ok. so i delete my app completely from android. Then on a fresh install i get the error

Field already exists in 'PortfolioCoin': color. 

Why is realm trying to migrate on a fresh install?

I got this in my application file

    Realm.init(this);
    RealmConfiguration configuration = new RealmConfiguration.Builder()
            .name(Realm.DEFAULT_REALM_NAME)
            .schemaVersion(1)
            .migration(new Migration())
            //.deleteRealmIfMigrationNeeded()
            .build();
    Realm.setDefaultConfiguration(configuration);

    Realm.compactRealm(configuration);

and this is my migration file

public class Migration implements RealmMigration {

@Override
public void migrate(final DynamicRealm realm, long oldVersion, long newVersion) {
    // During a migration, a DynamicRealm is exposed. A DynamicRealm is an untyped variant of a normal Realm, but
    // with the same object creation and query capabilities.
    // A DynamicRealm uses Strings instead of Class references because the Classes might not even exist or have been
    // renamed.

    // Access the Realm schema in order to create, modify or delete classes and their fields.
    RealmSchema schema = realm.getSchema();


    if (oldVersion == 0) {

        RealmObjectSchema portfolioCoinSchema = schema.get("PortfolioCoin");
        portfolioCoinSchema
                .addField("color", int.class)
                .addField("totalValueBTC", double.class);

        oldVersion++;
    }

}

}

like image 417
MrRed Avatar asked Jul 19 '17 00:07

MrRed


1 Answers

It happens because you're doing a fresh install, which already have the fields "color" and "totalValueBTC", and then you're trying to do a migration from 'oldVersion == 0', which is the default value.

So you're trying to add fields that already exist.

You should either check for a different version code, or you should use the "hasField(field)" method to check if it's already there, before trying to add it via a migration.

like image 64
Moonbloom Avatar answered Oct 17 '22 12:10

Moonbloom