Migrate list of RealmString -> String


#1

Hi!

How to correctly migrate a RealmList of RealmString/RealmInteger to a RealmList of String/Integer?

Before:

class MyClass extends RealmObject {
RealmList<RealmString> items;
}

New:

class MyClass extends RealmObject {
RealmList<String> items;
}

I’ve looked at several examples, but I don’t understand how to switch type of the items in the list. I guess that I could create a new list of String and loop over the old and add them to the new list, delete the old class member and rename the new one, but I don’t understand how to do that either. :slight_smile:

I tried something like this, but is it the correct way?

schema.get("MyClass")
.addRealmListField("items_temp", String.class)
.transform(new RealmObjectSchema.Function() {
	@Override
	public void apply(DynamicRealmObject obj) {
		RealmList<RealmString> oldList = obj.getList("items");
		RealmList<String> newList = obj.getList("items_temp");
		for (RealmString oldItem : oldList) {
			newList.add(oldItem.getString());
		}
	}
})
.removeField("items")
.renameField("items_temp", "items");

#2

Yes, that is the correct way to convert it.
Please notice that we don’t support query for primitive RealmList for now. If you need that, you may want to wait a bit longer.


#3

I tried something like this, but it complains on this line

RealmList<RealmString> oldList = obj.getList("items");
RealmList<String> newList = obj.getList("items_temp");

that it can’t cast RealmList<DynamicRealmObject> to RealmList<RealmString>.


#4
schema.get("MyClass")
.addRealmListField("items_temp", String.class)
.transform(new RealmObjectSchema.Function() {
	@Override
	public void apply(DynamicRealmObject obj) {
		RealmList<DynamicRealmObject> oldList = obj.getList("items");
		RealmList<String> newList = obj.getList("items_temp", String.class);
		for (DynamicRealmObject oldItem : oldList) {
			newList.add(oldItem.getString("string"));
		}
	}
})
.removeField("items")
.renameField("items_temp", "items");

#5

Here’s the method I created for multiple fields I needed to convert (based on others above and based on our old field name being called “value” in a custom “RealmString” RealmObject we had created):

    private void convertFieldFromRealmStringListToStringList(RealmObjectSchema schema, String fieldName) {
        schema.addRealmListField("items_temp", String.class)
              .transform(obj -> {
                  RealmList<DynamicRealmObject> oldList = obj.getList(fieldName);
                  RealmList<String> newList = obj.getList("items_temp", String.class);
                  for (DynamicRealmObject oldItem : oldList) {
                      String realmString = oldItem.get("value");
                      newList.add(realmString);
                  }
              })
              .removeField(fieldName)
              .renameField("items_temp", fieldName);
    }

Oh, and this uses lambdas with Java 8.