导入预先填充的Realm数据库

时间:2015-11-30 15:11:31

标签: android realm

我已经预填充了realm数据库,所以我有default.realm。我想在另一个应用程序中使用它,所以我把它放在我的\ res \ raw文件夹中。我读到它应该像调用Realm.getInstance()一样简单。我有这样的代码:

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

但它不起作用。我可以在我的app包中看到default.realm,所以我认为copyBundledRealmFile已被执行,但随后发生了io.realm.exceptions.RealmMigrationNeededException。我不知道是否有办法跳过迁移部分?因为我认为我实际上不会迁移,所以只需使用预先填充的数据库。编写迁移部分并不像调用Realm.getInstance()那么简单。

1 个答案:

答案 0 :(得分:0)

我刚遇到同样的问题。但问题出在我的模型定义中。我是手工制作的。

尝试在Realm Browser中打开数据库并为Java保存模型定义。我做到了,它解决了这个问题。

相关问题