Android Realm Database Export

Budi Oktaviyan
2 min readFeb 4, 2017

--

Hola bro! back again to my story. Right now I’ll share a little things about how to export realm file into your PC. It just because you wanna know if the database that you’ve been created or object you’ve just insert into realm are work properly for example :)

If you don’t know what is realm, you can go directly to this page. Ok let’s talk with simple example here. Assume that you’ve already add the realm plugin. I’ll create a RealmObject called User.

public class User extends RealmObject {

@PrimaryKey
private String email;

private String name;

public User() {
}

public String getEmail() {
return email;
}

public void setEmail(final String email) {
this.email = email;
}

public String getName() {
return name;
}

public void setName(final String name) {
this.name = name;
}
}

And initial RealmConfiguration as well like this

public class App extends Application {

@Override
public void onCreate() {
super.onCreate();
Realm.init(this);

final RealmConfiguration configuration = new RealmConfiguration.Builder().name("sample.realm").schemaVersion(1).build();
Realm.setDefaultConfiguration(configuration);
Realm.getInstance(configuration);

}

@Override
public void onTerminate() {
Realm.getDefaultInstance().close();
super.onTerminate();
}
}

Run your application and Realm automatically create that object inside schema file “sample.realm”. Then, go back to your activity/fragment class and add some function to export the realm file into your device external storage.

final Realm realm = Realm.getDefaultInstance();

try {
final File file = new File(Environment.getExternalStorageDirectory().getPath().concat("/sample.realm"));
if (file.exists()) {
//noinspection ResultOfMethodCallIgnored
file.delete();
}

realm.writeCopyTo(file);
Toast.makeText(MainActivity.this, "Success export realm file", Toast.LENGTH_SHORT).show();
} catch (IOException e) {
realm.close();
e.printStackTrace();
}

Don’t forget to add Read/Write Permission in your AndroidManifest. And if your device is running on Android API 23+, you have to add the Permissions checking for this :)

<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

Then, when you’re call the exporter function, your realm file already inside your external storage, you can pull them with “adb shell” command like this

adb pull /storage/sdcard0/sample.realm <your_computer_directory>

That’s it, you can open those realm file with a RealmBrowser like the following picture :)

Realm Browser on Mac

Ok, that’s all what I can share about realm exporter. For a sample source you can go through My Github of course :)

--

--

Budi Oktaviyan
Budi Oktaviyan

Written by Budi Oktaviyan

The only way to do great work, is to love what you do

Responses (3)