Import prepopulated Realm database

六月ゝ 毕业季﹏ 提交于 2020-01-14 14:16:49

问题


I have prepopulated realm database, so I have default.realm. I want to use it in another app so I put it in my \res\raw folder. I read that it should be as easy as calling Realm.getInstance(). I have code like this:

copyBundledRealmFile(this.getResources().openRawResource(R.raw.default0), "default.realm");

realm = Realm.getInstance(this);

private String copyBundledRealmFile(InputStream inputStream, String outFileName) {
        try {
            File file = new File(this.getFilesDir(), outFileName);
            FileOutputStream outputStream = new FileOutputStream(file);
            byte[] buf = new byte[1024];
            int bytesRead;
            while ((bytesRead = inputStream.read(buf)) > 0) {
                outputStream.write(buf, 0, bytesRead);
            }
            outputStream.close();
            return file.getAbsolutePath();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

But it doesn't work. I can see a default.realm in my app package, so I think copyBundledRealmFile was executed, but then io.realm.exceptions.RealmMigrationNeededException occurs. I don't know if there is a way to skip migration part? Because I think I don't actually migrate, just use prepopulated databse. And writing Migration part won't be as easy as calling Realm.getInstance().


回答1:


I just faced with the same problem. But the issue was in my model definition. I made it manually.

Try to open the database in Realm Browser and Save Model Definition for Java. I did it and it fixed the issue.



来源:https://stackoverflow.com/questions/34001760/import-prepopulated-realm-database

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!