【问题标题】:In Realm on android im getting "Field already exists" error but its on a fresh install?在 Android 上的 Realm 中,我得到“字段已存在”错误,但它是全新安装的?
【发布时间】:2025-12-21 21:00:09
【问题描述】:

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

Field already exists in 'PortfolioCoin': color. 

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

我在我的应用程序文件中找到了这个

    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);

这是我的迁移文件

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

}

}

【问题讨论】:

  • 您找到解决方案了吗?我遇到了同样的问题,但崩溃是在以前的迁移版本中。在我当前的应用中,迁移版本是 10,但崩溃发生在 if (oldVersion == 6)
  • 我在小米 Redmi Note 设备中遇到了这个问题。

标签: android migration realm


【解决方案1】:

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

所以您正在尝试添加已经存在的字段。

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

【讨论】:

  • 如果安装是全新的,则不需要迁移,因为没有旧版本
最近更新 更多