Navigation

Open & Close a Local Realm - Android SDK

To open a realm, create a RealmConfiguration with RealmConfiguration.Builder and pass the resulting RealmConfiguration to getInstance() or getInstanceAsync():

val config = RealmConfiguration.Builder()
.allowQueriesOnUiThread(true)
.allowWritesOnUiThread(true)
.build()
val realm = Realm.getInstance(config)
Log.v("EXAMPLE", "Successfully opened a realm at: ${realm.path}")
Tip
See also:

It is important to remember to call the close() method when done with a realm instance to free resources. Neglecting to close realms can lead to an OutOfMemoryError.

realm.close()

To configure settings for a realm, create a RealmConfiguration with a RealmConfiguration.Builder:

val config = RealmConfiguration.Builder()
.name("alternate-realm")
.allowQueriesOnUiThread(true)
.allowWritesOnUiThread(true)
.compactOnLaunch()
.inMemory()
.build()
val realm = Realm.getInstance(config)
Log.v("EXAMPLE", "Successfully opened a realm at: ${realm.path}")
Important
Synchronous Reads and Writes on the UI Thread

By default, you can only read or write to a realm in your application's UI thread using asynchronous transactions. That is, you can only use Realm methods whose name ends with the word Async in the main thread of your Android application unless you explicitly allow the use of synchronous methods.

This restriction exists for the benefit of your application users: performing read and write operations on the UI thread can lead to unresponsive or slow UI interactions, so it's usually best to handle these operations either asynchronously or in a background thread. However, if your application requires the use of synchronous realm reads or writes on the UI thread, you can explicitly allow the use of synchronous methods with the following SyncConfiguration options:

val config = SyncConfiguration.Builder(app.currentUser(), PARTITION)
.allowQueriesOnUiThread(true)
.allowWritesOnUiThread(true)
.build()
Realm.getInstanceAsync(config, object : Realm.Callback() {
override fun onSuccess(realm: Realm) {
Log.v("EXAMPLE", "Successfully opened a realm with reads and writes allowed on the UI thread.")
}
})

Use the readOnly() method when configuring your realm to make it read-only:

val config = RealmConfiguration.Builder()
.assetFile("readonly.realm")
.readOnly()
.modules(BundledRealmModule())
.build()

To create a realm that runs entirely in memory without being written to a file, use the inMemory() method when configuring your realm:

val config = RealmConfiguration.Builder()
.inMemory()
.name("kt.transient.realm")
.build()
val realm = Realm.getInstance(config)

To open a Dynamic Realm with a mutable schema, use DynamicRealm:

val config = RealmConfiguration.Builder()
.allowWritesOnUiThread(true)
.allowQueriesOnUiThread(true)
.name("kt.dynamic.realm")
.build()
val dynamicRealm = DynamicRealm.getInstance(config)
// all objects in a DynamicRealm are DynamicRealmObjects
var frog: DynamicRealmObject? = null
dynamicRealm.executeTransaction { transactionDynamicRealm: DynamicRealm ->
// add type Frog to the schema with name and age fields
dynamicRealm.schema
.create("Frog")
.addField("name", String::class.java)
.addField("age", Integer::class.java)
frog = transactionDynamicRealm.createObject("Frog")
frog?.set("name", "Wirt Jr.")
frog?.set("age", 42)
}
// access all fields in a DynamicRealm using strings
val name = frog?.getString("name")
val age = frog?.getInt("age")
// because an underlying schema still exists,
// accessing a field that does not exist throws an exception
try {
frog?.getString("doesn't exist")
} catch (e: IllegalArgumentException) {
Log.e("EXAMPLE", "That field doesn't exist.")
}
// Queries still work normally
val frogs = dynamicRealm.where("Frog")
.equalTo("name", "Wirt Jr.")
.findAll()

You can save any RealmConfiguration as the default for your application using the setDefaultConfiguration() method:

val config = RealmConfiguration.Builder()
.name("default-realm")
.allowQueriesOnUiThread(true)
.allowWritesOnUiThread(true)
.compactOnLaunch()
.inMemory()
.build()
// set this config as the default realm
Realm.setDefaultConfiguration(config)

You can then use the getDefaultConfiguration() or getDefaultInstance() methods to access that configuration, or an instance created from that configuration:

val realm = Realm.getDefaultInstance()
Log.v("EXAMPLE","Successfully opened the default realm at: ${realm.path}")

Realm modules are collections of Realm object models. You can selectively include individual modules when opening a realm.

Note

Libraries that include Realm Database must expose and use their schema through a module. Doing so prevents the library from generating the default RealmModule, which would conflict with the default RealmModule used by any app that includes the library. Apps using the library access library classes through the module.

// A library must create a module and set library = true. This will prevent the default
// module from being created.
// allClasses = true can be used instead of listing all classes in the library.
@RealmModule(library = true, allClasses = true)
class MyLibraryModule
// ...
// Library projects are therefore required to explicitly set their own module.
val libraryConfig =
SyncConfiguration.Builder(app.currentUser(), LIBRARY_PARTITION)
.modules(MyLibraryModule())
.build()
// Apps can add the library RealmModule to their own schema.
val config =
SyncConfiguration.Builder(app.currentUser(), PARTITION)
.modules(Realm.getDefaultModule(), MyLibraryModule())
.build()
Give Feedback