如何将数据从Sqlite迁移到Realm

How to migrate data from Sqlite to Realm

我将数据存储在 sqlite 数据库中,应用程序正在生产中。现在我正在考虑将数据从 Sqlite 迁移到 Realm DB。我有一个原始查询来从 Sqlite 读取数据,同时在迁移 class 中迁移到领域时,我试图将数据存储到领域中,但我没有成功。谁能帮我解决这个问题。

public class Test extends RealmObject { 
    @PrimaryKey
    private String name;
    private String sex; 
}



//Migration Class


@Override
protected void doMigration(final DynamicRealm dynamicRealm) {
    RealmSchema realmSchema = dynamicRealm.getSchema();

    if (!realmSchema.contains("Test")) {
        RealmObjectSchema testSchema = realmSchema.create("Test");
        testSchema.addField("name", String.class, FieldAttribute.PRIMARY_KEY);
        testSchema.addField("sex", String.class);


//Trying to migrate data store data to realm from sqlite during migration itself.

 testSchema.transform(new RealmObjectSchema.Function() {
    @Override
    public void apply(final DynamicRealmObject obj) {
        if (!sqlTest.isEmpty()) {  //data from Sqlite
            for (Test tempTest : sqlTest) { //looping for sqlite data
                obj.set("name", tempTest.getName();
                obj.set("sex", tempTest.getSex());
            }
        }
     });
}

transform 方法用于改变现有对象,例如添加具有默认值的列、重命名列等:https://realm.io/docs/java/latest/#migrations

创建模式后,您需要迭代 sql 值并在领域中添加数据,例如:

for (SqlTest sqlData : sqlTest) {
    Test test1 = realm.createObject(Test.class, UUID.randomUUID());
    test1.setName(sqlData.getName());
    test1.setSex(sqlData.getSex());
}
for (Test tempTest : sqlTest) {    ##sqlTest is data from Sqlite##
     DynamicRealmObject realmObject = dynamicRealm.createObject("Test", 'PrimaryKey'); 
     realmObject.set("name", tempTest.getname()); 
     realmObject.set("sex", tempTest.getsex()); 
    }