如何将数据从Sqlite迁移到Realm

时间:2019-03-17 20:10:38

标签: android sqlite realm android-sqlite data-migration

我将数据存储在sqlite DB中,并且该应用程序正在生产中。现在,我正在考虑将数据从Sqlite迁移到Realm DB。我有一个原始查询,可从Sqlite读取数据,并且在迁移类中迁移到领域时,我试图将数据存储到领域中,但未成功。有人可以帮我吗?

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());
            }
        }
     });
}

2 个答案:

答案 0 :(得分:2)

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());
}

答案 1 :(得分:0)

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()); 
    }