Giorgos Oikonomou Giorgos Oikonomou - 1 year ago 460
Android Question

Realm with pre populated data into assets?

Normally I use Realm as:

RealmConfiguration config = new RealmConfiguration.Builder(applicationContext).deleteRealmIfMigrationNeeded().build();

How can I add to the assets folder of my project a database with data and read it?

Answer Source

It is possible to bundle a Realm database in the assets folder, but then you just need to copy it from there when starting the app the first time.

We have an example of how to copy the files here:

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

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 = > 0) {
            outputStream.write(buf, 0, bytesRead);
        return file.getAbsolutePath();
    } catch (IOException e) {
    return null;