androidAhmed androidAhmed - 3 months ago 28
Android Question

use realm instance across different activities which using predefined realm database

I add predefined realm database to my app successufully and get the data

copyBundledRealmFile(this.getResources().openRawResource(R.raw.test),
"test");

RealmConfiguration config1 = new RealmConfiguration.Builder(this)
.name("test")
.schemaVersion(1)
.migration(new Migration())
.build();
realm = Realm.getInstance(config1);
realm.close();

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


the problem how to get instance of the realm when I try using

realm = Realm.getDefaultInstance();


give me empty data
how can get instance across the app

Answer

To be able to get a default, you have to set a default:

RealmConfiguration config1 = new RealmConfiguration.Builder(this)
        .name("test")
        .schemaVersion(1)
        .migration(new Migration())
        .build();

Realm.setDefaultConfiguration(config1); // <-- here

Now you can get it with

Realm.getDefaultInstance();
Comments