Open and Close a Realm

Open a Synced Realm

To open a synced realm, call getInstanceAsync(), passing in a a SyncConfiguration object. For example, the following code demonstrates how to create a realm with specific sync settings created using a SyncConfiguration object:

val user: User? = app.currentUser()
val partitionValue: String = "myPartition"
val config = SyncConfiguration.Builder(user!!, partitionValue).build()

val realm: Realm = Realm.getInstance(config)
User user = app.currentUser();
String partitionValue = "myPartition";
SyncConfiguration config =
   new SyncConfiguration.Builder(user, partitionValue).build();

Realm realm = Realm.getInstance(config);

The code above shows how to open the realm asynchronously by using getInstanceAsync(). You can also open a realm synchronously by using getInstance(), but this may lead to temporary data inconsistencies while the remote data is downloaded, and is generally not recommended.


To enable sync in your Android project, you need to configure it in the application-level build.gradle file by adding the following entry:

realm { syncEnabled = true }

For more information on enabling sync in Android, see Install Realm for Android.

Open a Local (Non-Synced) Realm

When opening a local (non-synced) realm, set the default settings and then call getDefaultInstance():

val config = RealmConfiguration.Builder().build()

val realm: Realm = Realm.getDefaultInstance()
RealmConfiguration realmConfig =
   new RealmConfiguration.Builder(this).build();

Realm realm = Realm.getDefaultInstance();

Close a Realm

It is important to remember to call the close() method when done with a realm instance. Failing to do so can lead to OutOfMemoryError as the native resources cannot be freed.

←   Realms Realm Objects  →