如何在Android中的Realm Migration上的新类上添加现有对象

pau*_*nku 4 android realm realm-migration

我有一个用于生产的应用程序,因此必须使用 RealmMigration

我看了文档和此示例,但没有找到以下方法。

在当前版本中,我有类型的项目,Fooboolean属性称为favorite。现在,我想对此进行概括并创建用户自定义Foo列表,以便用户能够创建其自定义列表并添加所需数量的对象。我想用一个名为UserFooListbasic name和a RealmList<Foo>的新类来实现这一点。

在迁移过程中,我将使用其字段创建此新类。

这很容易,但是困难之处在于:

我想将Foo标记有以前的所有项目添加favorite到新项目UserFooList,然后删除现在未使用Foo的字段favorite


一些代码可以帮助阐明:

当前课程

public class Foo extends RealmObject{

    private String title;
    private boolean favorite;

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public boolean isFavorite() {
        return favorite;
    }

    public void setFavorite(boolean favorite) {
        this.favorite = favorite;
    }
}
Run Code Online (Sandbox Code Playgroud)

班级变更

public class Foo extends RealmObject{

    //favorite field will be removed
    private String title;

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }
}
Run Code Online (Sandbox Code Playgroud)

新班

public class UserFooList extends RealmObject{

    private String name;
    private RealmList<Foo> items;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public RealmList<Foo> getItems() {
        return items;
    }

    public void setItems(RealmList<Foo> items) {
        this.items = items;
    }
}
Run Code Online (Sandbox Code Playgroud)

我想插入一个UserFooList实例并使用以下实例进行填充:

  • name:“收藏夹”
  • items:所有现有Foo实例favorite == true

我想在迁移过程中这样做,因为这样一来,我便可以favorite在将所有元素插入新创建的列表后删除字段。

Epi*_*rce 6

依靠DynamicRealm API的强大功能。

public class MyMigration implements Realm.Migration {    
    @Override
    public void migrate(DynamicRealm realm, long oldVersion, long newVersion) {
        RealmSchema schema = realm.getSchema();
        if(oldVersion == 0) {
            RealmObjectSchema foo = schema.get("Foo");
            RealmObjectSchema userFooList = schema.create("UserFooList");
            userFooList.addField("name", String.class);
            userFooList.addRealmListField("items", foo);

            DynamicRealmObject userList = realm.createObject("UserFooList");
            userList.setString("name", "favorites");
            RealmList<DynamicRealmObject> listItems = userList.getList("items");
            RealmResults<DynamicRealmObject> favoriteFoos = realm.where("Foo").equalTo("favorite", true).findAll();
            for(DynamicRealmObject fooObj: favoriteFoos) {
                listItems.add(fooObj);
            }
            foo.removeField("favorite");
            oldVersion++;
        }
    }

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

    @Override public int hashCode() {
        return MyMigration.class.hashCode();
    }
}
Run Code Online (Sandbox Code Playgroud)