导入预填充的Realm数据库 [英] Import prepopulated Realm database

查看:94
本文介绍了导入预填充的Realm数据库的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经预填充了领域数据库,所以我具有default.realm.我想在另一个应用程序中使用它,因此将其放在我的\ res \ raw文件夹中.我读到它应该像调用Realm.getInstance()一样容易.我有这样的代码:

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

但是它不起作用.我可以在我的应用程序包中看到default.realm,因此我认为执行了copyBundledRealmFile,但是随后发生io.realm.exceptions.RealmMigrationNeededException.我不知道是否可以跳过迁移部分吗?因为我认为我实际上并不迁移,所以请使用预填充的数据库.而且编写迁移"部分不会像调用Realm.getInstance()那样容易.

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().

推荐答案

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

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

尝试在Realm Browser中打开数据库并保存Java的Model Definition.我做到了,它解决了这个问题.

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

这篇关于导入预填充的Realm数据库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆