问题
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