Android Realm迁移:使用另一个对象切换嵌套对象,两个对象都扩展了RealmObject

时间:2019-06-29 11:22:20

标签: android realm realm-migration

我正面临以下问题。

我有一堂课想保存到领域中。在该类中,我有一个嵌套的领域对象,可以说要与CoinB切换的CoinA。

class Transaction extends RealmObject {
    @PrimaryKey
    private int id;

    private CoinA coin;

    ... // more fields

class CoinA extends RealmObject implements Parcelable {
   @PrimaryKey
   private int id; 

   private String urlSourceToCCCoin;

   ...// more fields

class CoinB extends RealmObject implements Parcelable {
   @PrimaryKey
   private String id;

   private String imageUrl;

   ...//and may more fields different than fields from CoinA

预期班级:

class Transaction extends RealmObject {
    @PrimaryKey
    private int id;

    private CoinB coin;

    ... // more fields

我非常确定以下各项将起作用,但没有用。我找到了一个与我要找的答案非常接近的答案,但是它对我没有用。遵循Migrate realm field of type double to new sub-object with values

中显示的逻辑
class NewRealmMigration extends RealmMigration {

@Override
public void migrate(DynamicRealm realm, long oldVersion, long newVersion){
        RealmSchema realmSchema = realm.getSchema();
        // Building the schema for CoinB
        RealmObjectSchema coinBObjectSchema = realmSchema.create("CoinB")
                .addField("id", String.class)
                .addField("imageUrl", String.class)
                ... //more fields

        realmSchema.get("Transaction")
                .addRealmObjectField("coin_tmp", coinBObjectSchema)
                .transform(new RealmObjectSchema.Function() {
                    @Override
                    public void apply(DynamicRealmObject realmObject) {
                        DynamicRealmObject coinA = realmObject.getObject("coin");
                        DynamicRealmObject coinB = realmObject.getObject("coin_tmp");

                        coinB.setString("id", String.valueOf(coinA.getInt(ID)));
                        coinB.setString("imageUrl", coinA.getString("sourceImageUrl"));
                        ... //more fields
                    }
                })
                .removeField("coin")
                .renameField("coin_tmp", "coin");
    }
}

我希望上述迁移能够正常工作,但事实并非如此。尽管在调用.addRealmObjectField("coin_tmp", coinBObjectSchema)时在transform方法块中添加了DynamicRealmObject coinB = realmObject.getObject("coin_tmp");,它 ALWAYS返回null ,但我无法设置新对象的字段,并且应用程序崩溃。

根据我遵循的答案,它不应返回null而是对新创建对象的引用。不幸的是,这似乎没有发生。也许我缺少某些东西或做错了什么。

感谢您的帮助

0 个答案:

没有答案