在 Android 上的 Realm 中,我收到“字段已存在”错误,但它是全新安装的?

MrR*_*Red 5 migration android realm

好的。所以我从Android中完全删除了我的应用程序。然后在全新安装时出现错误

Field already exists in 'PortfolioCoin': color. 
Run Code Online (Sandbox Code Playgroud)

为什么领域尝试在全新安装上迁移?

我在我的申请文件中找到了这个

    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);
Run Code Online (Sandbox Code Playgroud)

这是我的迁移文件

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++;
    }

}
Run Code Online (Sandbox Code Playgroud)

}

Moo*_*oom 4

发生这种情况是因为您正在进行全新安装,其中已经具有“color”和“totalValueBTC”字段,然后您尝试从默认值“oldVersion == 0”进行迁移。

因此,您正在尝试添加已经存在的字段。

您应该检查不同的版本代码,或者应该使用“hasField(field)”方法检查它是否已经存在,然后再尝试通过迁移添加它。