简体   繁体   English

如何在 Android 中进行 Realm 迁移?

[英]How to do a Realm migration in Android?

I'm using Realms as a database in Android app.我在 Android 应用程序中使用 Realms 作为数据库。 Works fine, but I've added a new label in my user model and I'm getting the error that I need to migrate my schema:工作正常,但我在我的用户模型中添加了一个新标签,但出现了我需要迁移架构的错误:

java.lang.RuntimeException: Unable to create application com.apelucy.apelucy.app.base.MyApplication: io.realm.exceptions.RealmMigrationNeededException: Migration is required due to the following errors:
                                                   - Property 'User.testRealm' has been added.

How can I do the migration?我该如何进行迁移? I've found other solutions here but I can't implement them in my code.我在这里找到了其他解决方案,但我无法在我的代码中实现它们。 I can't use a solution of delete and install the app.我无法使用删除和安装应用程序的解决方案。 I now that work in development, but I need to update the app in production.我现在正在开发中,但我需要在生产中更新应用程序。

My UserRespository class:我的 UserRespository 类:

public class UserRepository {

    private static UserRepository sInstance = null;
    private Context mContext = null;



    public static UserRepository getInstance(Context context) {
        if (sInstance == null) {
            sInstance = new UserRepository();
            sInstance.mContext = context;
        }

        return sInstance;
    }

    // DATABASE Methods

    public void storeUser(final User user) {
        AppSingleton.getInstance().setUser(user);

        Realm realm = null;
        try {
            realm = Realm.getDefaultInstance();
            realm.executeTransaction(realm1 -> realm1.insertOrUpdate(user));
        } finally {
            if (realm != null) {
                realm.close();
            }
        }
    }

    public User retrieveUser() {
        Realm realm = null;
        User user = null;
        try {
            realm = Realm.getDefaultInstance();
            User userRealmResult = realm.where(User.class)
                    .findFirst();

            if (userRealmResult != null) {
                user = realm.copyFromRealm(userRealmResult);
            }

        } finally {
            if (realm != null) {
                realm.close();
            }
        }

        return user;
    }

    public void clearUser() {
        // Clear Database objects
        Realm realm = null;
        try {
            realm = Realm.getDefaultInstance();
            realm.executeTransaction(realm1 -> realm1.delete(User.class));
        } finally {
            if (realm != null) {
                realm.close();
            }
        }
    }
}

Init realm in my Application:在我的应用程序中初始化领域:

Realm.init(this);

My model change:我的模型变化:

@SerializedName("test")
@Expose
private String testRealm;

Migrations allow you to modify the schema of the application, which means that it lets you add, remove, rename tables/fields in the Realm schema.迁移允许您修改应用程序的架构,这意味着它允许您添加、删除、重命名 Realm 架构中的表/字段。 If you change a RealmModel class, then you must write the migration that will map the existing Realm file to reflect the new model classes.如果您更改 RealmModel 类,则必须编写将映射现有 Realm 文件以反映新模型类的迁移。

RealmConfiguration config = new RealmConfiguration.Builder()
                                 .schemaVersion(1)
                                 .migration(new MyMigration()) 
                                 .build();
Realm.setDefaultConfiguration(config);

The default schema version is 0.默认架构版本为 0。


Migrations are fairly straightforward:迁移相当简单:

  • you must increment the schema version, so Realm knows you want to increment the schema's version to a specific number你必须增加模式版本,所以 Realm 知道你想增加模式的版本到一个特定的数字

  • you must supply a migration that will handle the change from one version to another您必须提供一个迁移来处理从一个版本到另一个版本的更改

Migrations describe the operations to do when you need to go from one schema version to another:迁移描述了当您需要从一个架构版本迁移到另一个架构版本时要执行的操作:

public class MyMigration implements RealmMigration {

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

        // Migrate from version 0 to version 1
        if (oldVersion == 0) {
            RealmObjectSchema userSchema = schema.get("User");

            userSchema.addField("testRealm", String.class);
            oldVersion++;
        }

        if (oldVersion == 1) { // ...
            // ...
        }
    }

    @Override
    public int hashCode() { return MyMigration.class.hashCode(); }

    @Override
    public boolean equals(Object object) { return object != null && object instanceof MyMigration; }
}

Add this in your Application file.将此添加到您的应用程序文件中。 This will Realm to delete everything if you add a new table to a column.如果您向列添加新表,这将使 Realm 删除所有内容。

RealmConfiguration config = new RealmConfiguration.Builder().name("dbname.realm")
                                     .deleteRealmIfMigrationNeeded()
                                     .build();
Realm.setDefaultConfiguration(config);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM