Class Realm
On this page
- io.realm
- Nested Class Summary
- Field Summary
- Method Summary
- Inherited Methods
- Field Detail
DEFAULT_REALM_NAME
ENCRYPTION_KEY_LENGTH
- Method Detail
- addChangeListener
- asFlowable
- compactRealm
- copyFromRealm
- copyToRealm
- copyToRealmOrUpdate
- createAllFromJson
- createEmbeddedObject
- createObject
- createObjectFromJson
- createOrUpdateAllFromJson
- createOrUpdateObjectFromJson
- delete
- deleteRealm
- executeTransaction
- executeTransactionAsync
- freeze
- getApplicationContext
- getDefaultConfiguration
- getDefaultInstance
- getDefaultModule
- getGlobalInstanceCount
- getInstance
- getInstanceAsync
- getLocalInstanceCount
- getSchema
- init
- insert
- insertOrUpdate
- isEmpty
- migrateRealm
- removeAllChangeListeners
- removeChangeListener
- removeDefaultConfiguration
- setDefaultConfiguration
- where
io.realm
The Realm class is the storage and transactional manager of your object persistent store. It is in charge of creating instances of your RealmObjects. Objects within a Realm can be queried and read at any time. Creating, modifying, and deleting objects must be done while inside a transaction. See executeTransaction(Transaction)
The transactions ensure that multiple instances (on multiple threads) can access the same objects in a consistent state with full ACID guarantees.
It is important to remember to call the close() method when done with a Realm instance. Failing to do so can lead to java.lang.OutOfMemoryError as the native resources cannot be freed.
Realm instances cannot be used across different threads. This means that you have to open an instance on each thread you want to use Realm. Realm instances are cached automatically per thread using reference counting, so as long as the reference count doesn't reach zero, calling getInstance(RealmConfiguration) will just return the cached Realm and should be considered a lightweight operation.
For the UI thread this means that opening and closing Realms should occur in either onCreate/onDestroy or onStart/onStop.
Realm instances coordinate their state across threads using the android.os.Handler mechanism. This also means that Realm instances on threads without an android.os.Looper cannot receive updates unless refresh() is manually called.
A standard pattern for working with Realm in Android activities can be seen below:
public class RealmApplication extends Application { public void onCreate() { super.onCreate(); // The Realm file will be located in package's "files" directory. RealmConfiguration realmConfig = new RealmConfiguration.Builder(this).build(); Realm.setDefaultConfiguration(realmConfig); } } public class RealmActivity extends Activity { private Realm realm; protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.layout_main); realm = Realm.getDefaultInstance(); } protected void onDestroy() { super.onDestroy(); realm.close(); } }
Realm supports String and byte fields containing up to 16 MB.
Nested Class Summary
Modifier and Type | Class and Description |
---|---|
public static interface | |
public abstract static |
Field Summary
Modifier and Type | Field and Description |
---|---|
public static final String | |
public static final int | The required length for encryption keys used to encrypt Realm data. |
Method Summary
Modifier and Type | Method and Description |
---|---|
public void | Adds a change listener to the Realm. |
public <any> | asFlowable () Returns an RxJava Flowable that monitors changes to this Realm. |
public static boolean | Compacts a Realm file. |
public E | Makes an unmanaged in-memory copy of an already persisted RealmObject . |
public E | Makes an unmanaged in-memory copy of an already persisted RealmObject . |
public List | Makes an unmanaged in-memory copy of already persisted RealmObjects. |
public List | Makes an unmanaged in-memory copy of already persisted RealmObjects. |
public List | Copies a collection of RealmObjects to the Realm instance and returns their copy. |
public E | Copies a RealmObject to the Realm instance and returns the copy. |
public List | Updates a list of existing RealmObjects that is identified by their io.realm.annotations.PrimaryKey or creates a new copy if no existing object could be found. |
public E | Updates an existing RealmObject that is identified by the same io.realm.annotations.PrimaryKey or creates a new copy if no existing object could be found. |
public void | Creates a Realm object for each object in a JSON array. |
public E | Instantiates and adds a new embedded object to the Realm. |
public E | Instantiates and adds a new object to the Realm with the primary key value already set. |
public E | Instantiates and adds a new object to the Realm. |
public E | Creates a Realm object pre-filled with data from a JSON object. |
public void | Tries to update a list of existing objects identified by their primary key with new JSON data. |
public E | Tries to update an existing object defined by its primary key with new JSON data. |
public void | Deletes all objects of the specified class from the Realm. |
public static boolean | Deletes the Realm file along with the related temporary files specified by the given RealmConfiguration from the filesystem. |
public void | Executes a given transaction on the Realm. |
public RealmAsyncTask | Realm.Transaction transaction, Realm.Transaction.OnSuccess onSuccess, Realm.Transaction.OnError onError ) Similar to executeTransactionAsync(Transaction) , but also accepts an OnSuccess and OnError callbacks. |
public RealmAsyncTask | Similar to executeTransactionAsync(Transaction) , but also accepts an OnError callback. |
public RealmAsyncTask | Similar to executeTransactionAsync(Transaction) , but also accepts an OnSuccess callback. |
public RealmAsyncTask | Similar to executeTransaction(Transaction) but runs asynchronously on a worker thread. |
public Realm | freeze () Returns a frozen snapshot of the current Realm. |
public static Context | Get the application context used when initializing Realm with Realm.init(Context) or Realm.init(Context, String) . |
public static RealmConfiguration | Returns the default configuration for getDefaultInstance() . |
public static Realm | Realm static constructor that returns the Realm instance defined by the io.realm.RealmConfiguration set by setDefaultConfiguration(RealmConfiguration) |
public static Object | Returns the default Realm module. |
public static int | Returns the current number of open Realm instances across all threads in current process that are using this configuration. |
public static Realm | Realm static constructor that returns the Realm instance defined by provided io.realm.RealmConfiguration |
public static RealmAsyncTask | The creation of the first Realm instance per RealmConfiguration in a process can take some time as all initialization code need to run at that point (setting up the Realm, validating schemas and creating initial data). |
public static int | Returns the current number of open Realm instances on the thread calling this method. |
public RealmSchema | getSchema () Returns the schema for this Realm. |
public static synchronized void | |
public static synchronized void | Initializes the Realm library and creates a default configuration that is ready to use. |
public void | Inserts an unmanaged RealmObject. |
public void | Inserts a list of an unmanaged RealmObjects. |
public void | Inserts or updates an unmanaged RealmObject. |
public void | Inserts or updates a list of unmanaged RealmObjects. |
public boolean | isEmpty () Checks if this io.realm.Realm contains any objects. |
public static void | Manually triggers a migration on a RealmMigration. |
public static void | Manually triggers the migration associated with a given RealmConfiguration. |
public void | Removes all user-defined change listeners. |
public void | Removes the specified change listener. |
public static void | Removes the current default configuration (if any). |
public static void | Sets the io.realm.RealmConfiguration used when calling getDefaultInstance() . |
public RealmQuery | Returns a typed RealmQuery, which can be used to query for specific objects of this type |
Inherited Methods
Methods inherited from class java.lang.Object :
getClass
,hashCode
,equals
,clone
,toString
,notify
,notifyAll
,wait
,wait
,wait
,finalize
Methods inherited from class io.realm.BaseRealm:
setAutoRefresh
,isAutoRefresh
,refresh
,isInTransaction
,addListener
,removeListener
,asFlowable
,removeAllListeners
,writeCopyTo
,writeEncryptedCopyTo
,waitForChange
,stopWaitForChange
,beginTransaction
,commitTransaction
,cancelTransaction
,freeze
,isFrozen
,getNumberOfActiveVersions
,checkIfValid
,checkAllowQueriesOnUiThread
,checkAllowWritesOnUiThread
,checkIfInTransaction
,checkIfValidAndInTransaction
,getPath
,getConfiguration
,getVersion
,close
,isClosed
,isEmpty
,getSchema
,getSubscriptions
,deleteAll
,migrateRealm
,finalize
Field Detail
DEFAULT_REALM_NAME
ENCRYPTION_KEY_LENGTH
The required length for encryption keys used to encrypt Realm data.
Method Detail
addChangeListener
Adds a change listener to the Realm.The listeners will be executed when changes are committed by this or another thread. Realm instances are per thread singletons and cached, so listeners should be removed manually even if calling close(). Otherwise there is a risk of memory leaks. Parameters
Throws
|
asFlowable
public <any> asFlowable () | ||||||
---|---|---|---|---|---|---|
Returns an RxJava Flowable that monitors changes to this Realm. It will emit the current state when subscribed to. Items will continually be emitted as the Realm is updated - Items emitted from Realm Flowables are frozen (See freeze(). This means that they are immutable and can be read on any thread. Realm Flowables always emit items from the thread holding the live Realm. This means that if you need to do further processing, it is recommend to observe the values on a computation scheduler:
If you would like the
Returns RxJava Observable that only calls Overrides
|
compactRealm
Compacts a Realm file. A Realm file usually contain free/unused space. This method removes this free space and the file size is thereby reduced. Objects within the Realm files are untouched.The file must be closed before this method is called, otherwise The file system should have free space for at least a copy of the Realm file. The Realm file is left untouched if any file operation fails. Parameters
Returns
|
copyFromRealm
Makes an unmanaged in-memory copy of an already persisted RealmObject . This is a deep copy that will copy all referenced objects up to the defined depth. The copied object(s) are all detached from Realm and they will no longer be automatically updated. This means that the copied objects might contain data that are no longer consistent with other managed Realm objects. *WARNING*: Any changes to copied objects can be merged back into Realm using copyToRealmOrUpdate(RealmModel, ImportFlag...) , but all fields will be overridden, not just those that were changed. This includes references to other objects even though they might be Type Parameters
Parameters
Returns an in-memory detached copy of the managed RealmObject . Throws
|
Makes an unmanaged in-memory copy of an already persisted RealmObject . This is a deep copy that will copy all referenced objects. The copied object(s) are all detached from Realm and they will no longer be automatically updated. This means that the copied objects might contain data that are no longer consistent with other managed Realm objects. *WARNING*: Any changes to copied objects can be merged back into Realm using copyToRealmOrUpdate(RealmModel, ImportFlag...) , but all fields will be overridden, not just those that were changed. This includes references to other objects, and can potentially override changes made by other threads. This behaviour can be modified using ImportFlag s. Type Parameters
Parameters
Returns an in-memory detached copy of the managed RealmObject . Throws
|
Makes an unmanaged in-memory copy of already persisted RealmObjects. This is a deep copy that will copy all referenced objects up to the defined depth.The copied objects are all detached from Realm and they will no longer be automatically updated. This means that the copied objects might contain data that are no longer consistent with other managed Realm objects. *WARNING*: Any changes to copied objects can be merged back into Realm using copyToRealmOrUpdate(Iterable, ImportFlag...) , but all fields will be overridden, not just those that were changed. This includes references to other objects even though they might be Type Parameters
Parameters
Returns an in-memory detached copy of the RealmObjects. Throws
|
Makes an unmanaged in-memory copy of already persisted RealmObjects. This is a deep copy that will copy all referenced objects.The copied objects are all detached from Realm and they will no longer be automatically updated. This means that the copied objects might contain data that are no longer consistent with other managed Realm objects. *WARNING*: Any changes to copied objects can be merged back into Realm using copyToRealmOrUpdate(RealmModel, ImportFlag...) , but all fields will be overridden, not just those that were changed. This includes references to other objects, and can potentially override changes made by other threads. This behaviour can be modified using ImportFlag s. Type Parameters
Parameters
Returns an in-memory detached copy of managed RealmObjects. Throws
|
copyToRealm
Copies a collection of RealmObjects to the Realm instance and returns their copy. Any further changes to the original RealmObjects will not be reflected in the Realm copies. This is a deep copy i.e., all referenced objects will be copied. Objects already in this Realm will be ignored.Please note, copying an object will copy all field values. Any unset field in the objects and child objects will be set to their default value if not provided. Parameters
Returns a list of the the converted RealmObjects that all has their properties managed by the Realm. Throws
|
Copies a RealmObject to the Realm instance and returns the copy. Any further changes to the original RealmObject will not be reflected in the Realm copy. This is a deep copy, so all referenced objects will be copied. Objects already in this Realm will be ignored.Please note, copying an object will copy all field values. Any unset field in this and child objects will be set to their default value if not provided. Parameters
Returns a managed RealmObject with its properties backed by the Realm. Throws
|
copyToRealmOrUpdate
Updates a list of existing RealmObjects that is identified by their io.realm.annotations.PrimaryKey or creates a new copy if no existing object could be found. This is a deep copy or update i.e., all referenced objects will be either copied or updated. Please note, copying an object will copy all field values. Any unset field in the objects and child objects will be set to their default value if not provided. Parameters
Returns a list of all the new or updated RealmObjects. Throws
|
Updates an existing RealmObject that is identified by the same io.realm.annotations.PrimaryKey or creates a new copy if no existing object could be found. This is a deep copy or update i.e., all referenced objects will be either copied or updated. Please note, copying an object will copy all field values. Any unset field in the object and child objects will be set to their default value if not provided. Parameters
Returns the new or updated RealmObject with all its properties backed by the Realm. Throws
|
createAllFromJson
Creates a Realm object for each object in a JSON array. This must be done within a transaction.JSON properties with unknown properties will be ignored. If a RealmObject field is not present in the JSON object the RealmObject field will be set to the default value for that type. This method currently does not support value list field. Parameters
Throws
|
createEmbeddedObject
public E createEmbeddedObject <E >( ) |
---|
Instantiates and adds a new embedded object to the Realm.This method should only be used to create objects of types marked as embedded. Parameters
Returns the newly created embedded object. Throws
|
createObject
Instantiates and adds a new object to the Realm with the primary key value already set.If the value violates the primary key constraint, no object will be added and a RealmException will be thrown. The default value for primary key provided by the model class will be ignored. Parameters
Returns the new object. Throws
|
Instantiates and adds a new object to the Realm.This method is only available for model classes with no @PrimaryKey annotation. If you like to create an object that has a primary key, use createObject(Class, Object) or copyToRealm(RealmModel, ImportFlag...) instead. Parameters
Returns the new object. Throws
|
createObjectFromJson
Creates a Realm object pre-filled with data from a JSON object. This must be done inside a transaction. JSON properties with unknown properties will be ignored. If a RealmObject field is not present in the JSON object the RealmObject field will be set to the default value for that type. This method currently does not support value list field. Parameters
Returns created object or Throws
TipSee also:
|
createOrUpdateAllFromJson
Tries to update a list of existing objects identified by their primary key with new JSON data. If an existing object could not be found in the Realm, a new object will be created. This must happen within a transaction. If updating a RealmObject and a field is not found in the JSON object, that field will not be updated. If a new RealmObject is created and a field is not found in the JSON object, that field will be assigned the default value for the field type. This method currently does not support value list field. Parameters
Throws
|
createOrUpdateObjectFromJson
Tries to update an existing object defined by its primary key with new JSON data. If no existing object could be found a new object will be saved in the Realm. This must happen within a transaction. If updating a RealmObject and a field is not found in the JSON object, that field will not be updated. If a new RealmObject is created and a field is not found in the JSON object, that field will be assigned the default value for the field type. This method currently does not support value list field. Parameters
Returns created or updated io.realm.RealmObject . Throws
|
delete
Deletes all objects of the specified class from the Realm. Parameters
Throws
|
deleteRealm
Deletes the Realm file along with the related temporary files specified by the given RealmConfiguration from the filesystem. Temporary file with ".lock" extension won't be deleted. All Realm instances must be closed before calling this method. WARNING: For synchronized Realm, there is a chance that an internal Realm instance on the background thread is not closed even all the user controlled Realm instances are closed. This will result an Parameters
Returns
Throws
|
executeTransaction
Executes a given transaction on the Realm. beginTransaction() and commitTransaction() will be called automatically. If any exception is thrown during the transaction cancelTransaction() will be called instead of commitTransaction(). Calling this method from the UI thread will throw a RealmException . Doing so may result in a drop of frames or even ANRs. We recommend calling this method from a non-UI thread or using executeTransactionAsync(Transaction) instead. Parameters
Throws
|
executeTransactionAsync
public RealmAsyncTask executeTransactionAsync ( Realm.Transaction transaction, Realm.Transaction.OnSuccess onSuccess, Realm.Transaction.OnError onError ) |
---|
Similar to executeTransactionAsync(Transaction) , but also accepts an OnSuccess and OnError callbacks. Parameters
Returns a RealmAsyncTask representing a cancellable task. Throws
|
public RealmAsyncTask executeTransactionAsync ( Realm.Transaction transaction, Realm.Transaction.OnError onError ) |
---|
Similar to executeTransactionAsync(Transaction) , but also accepts an OnError callback. Parameters
Returns a RealmAsyncTask representing a cancellable task. Throws
|
public RealmAsyncTask executeTransactionAsync ( Realm.Transaction transaction, Realm.Transaction.OnSuccess onSuccess ) |
---|
Similar to executeTransactionAsync(Transaction) , but also accepts an OnSuccess callback. Parameters
Returns a RealmAsyncTask representing a cancellable task. Throws
|
Similar to executeTransaction(Transaction) but runs asynchronously on a worker thread. Parameters
Returns a RealmAsyncTask representing a cancellable task. Throws
|
freeze
Returns a frozen snapshot of the current Realm. This Realm can be read and queried from any thread without throwing an IllegalStateException . A frozen Realm has its own lifecycle and can be closed by calling close(), but fully closing the Realm that spawned the frozen copy will also close the frozen Realm. Frozen data can be queried as normal, but trying to mutate it in any way or attempting to register any listener will throw an IllegalStateException . Note: Keeping a large number of Realms with different versions alive can have a negative impact on the filesize of the Realm. In order to avoid such a situation, it is possible to set RealmConfiguration.Builder.maxNumberOfActiveVersions(long) . Returns a frozen copy of this Realm. Overrides
|
getApplicationContext
public static Context getApplicationContext () |
---|
Get the application context used when initializing Realm with Realm.init(Context) or Realm.init(Context, String) . Returns the application context used when initializing Realm with Realm.init(Context) or Realm.init(Context, String) , or null if Realm has not been initialized yet. |
getDefaultConfiguration
public static RealmConfiguration getDefaultConfiguration () |
---|
Returns the default configuration for getDefaultInstance() . Returns default configuration object or |
getDefaultInstance
public static Realm getDefaultInstance () |
---|
Realm static constructor that returns the Realm instance defined by the io.realm.RealmConfiguration set by setDefaultConfiguration(RealmConfiguration) Returns an instance of the Realm class. Throws
|
getDefaultModule
public static Object getDefaultModule () |
---|
Returns the default Realm module. This module contains all Realm classes in the current project, but not those from library or project dependencies. Realm classes in these should be exposed using their own module. Returns the default Realm module or Throws
|
getGlobalInstanceCount
Returns the current number of open Realm instances across all threads in current process that are using this configuration. This includes both dynamic and normal Realms. Parameters
Returns number of open Realm instances across all threads. |
getInstance
Realm static constructor that returns the Realm instance defined by provided io.realm.RealmConfiguration Parameters
Returns an instance of the Realm class Throws
|
getInstanceAsync
public static RealmAsyncTask getInstanceAsync ( RealmConfiguration configuration, Realm.Callback callback ) |
---|
The creation of the first Realm instance per RealmConfiguration in a process can take some time as all initialization code need to run at that point (setting up the Realm, validating schemas and creating initial data). This method places the initialization work in a background thread and deliver the Realm instance to the caller thread asynchronously after the initialization is finished. Parameters
Returns a RealmAsyncTask representing a cancellable task. Throws
|
getLocalInstanceCount
Returns the current number of open Realm instances on the thread calling this method. This include both dynamic and normal Realms. Parameters
Returns number of open Realm instances on the caller thread. |
getSchema
public RealmSchema getSchema () |
---|
Returns the schema for this Realm. The schema is immutable. Any attempt to modify it will result in an UnsupportedOperationException . The schema can only be modified using DynamicRealm.getSchema() or through an migration. Returns The RealmSchema for this Realm. Overrides
|
init
Initializes the Realm library and creates a default configuration that is ready to use. It is required to call this method before interacting with any other of the Realm API's.A good place is in an android.app.Application subclass:
Remember to register it in the
Parameters
Throws
|
Initializes the Realm library and creates a default configuration that is ready to use. It is required to call this method before interacting with any other of the Realm API's.A good place is in an android.app.Application subclass:
Remember to register it in the
Parameters
Throws
|
insert
Inserts an unmanaged RealmObject. This is generally faster than copyToRealm(RealmModel, ImportFlag...) since it doesn't return the inserted elements, and performs minimum allocations and checks. After being inserted any changes to the original object will not be persisted. Please note:
If you want the managed RealmObject returned, use copyToRealm(RealmModel, ImportFlag...) , otherwise if you have a large number of object this method is generally faster. Parameters
Throws
|
Inserts a list of an unmanaged RealmObjects. This is generally faster than copyToRealm(Iterable, ImportFlag...) since it doesn't return the inserted elements, and performs minimum allocations and checks. After being inserted any changes to the original objects will not be persisted. Please note:
If you want the managed RealmObject returned, use copyToRealm(Iterable, ImportFlag...) , otherwise if you have a large number of object this method is generally faster. Parameters
Throws
|
insertOrUpdate
Inserts or updates an unmanaged RealmObject. This is generally faster than copyToRealmOrUpdate(RealmModel, ImportFlag...) since it doesn't return the inserted elements, and performs minimum allocations and checks. After being inserted any changes to the original object will not be persisted. Please note:
If you want the managed RealmObject returned, use copyToRealm(RealmModel, ImportFlag...) , otherwise if you have a large number of object this method is generally faster. Parameters
Throws
|
Inserts or updates a list of unmanaged RealmObjects. This is generally faster than copyToRealmOrUpdate(Iterable, ImportFlag...) since it doesn't return the inserted elements, and performs minimum allocations and checks. After being inserted any changes to the original objects will not be persisted. Please note:
If you want the managed RealmObject returned, use copyToRealm(Iterable, ImportFlag...) , otherwise if you have a large number of object this method is generally faster. Parameters
Throws
|
isEmpty
public boolean isEmpty () |
---|
Checks if this io.realm.Realm contains any objects. Returns
Overrides
|
migrateRealm
Manually triggers a migration on a RealmMigration. Parameters
Throws
|
Manually triggers the migration associated with a given RealmConfiguration. If Realm is already at the latest version, nothing will happen. Parameters
Throws
|
removeAllChangeListeners
public void removeAllChangeListeners () |
---|
Removes all user-defined change listeners. Throws
|
removeChangeListener
Removes the specified change listener. Parameters
Throws
|
removeDefaultConfiguration
public static void removeDefaultConfiguration () |
---|
Removes the current default configuration (if any). Any further calls to getDefaultInstance() will fail until a new default configuration has been set using setDefaultConfiguration(RealmConfiguration) . |
setDefaultConfiguration
Sets the io.realm.RealmConfiguration used when calling getDefaultInstance() . Parameters
Throws
|
where
Returns a typed RealmQuery, which can be used to query for specific objects of this type Parameters
Returns a typed RealmQuery, which can be used to query for specific objects of this type. |