Class DynamicRealm
- java.lang.Object
-
- io.realm.DynamicRealm
-
- All Implemented Interfaces:
Closeable
,AutoCloseable
public class DynamicRealm extends Object
DynamicRealm is a dynamic variant ofRealm
. This means that all access to data and/or queries are done using string based class names instead of class type references.This is useful during migrations or when working with string-based data like CSV or XML files.
The same
RealmConfiguration
can be used to open a Realm file in both dynamic and typed mode, but modifying the schema while having both a typed and dynamic version open is highly discouraged and will most likely crash the typed Realm. During migrations only a DynamicRealm will be open.Dynamic Realms do not enforce schemas or schema versions and
RealmMigration
code is not used even if it has been defined in theRealmConfiguration
.This means that the schema is not created or validated until a Realm has been opened in typed mode. If a Realm file is opened in dynamic mode first it will not contain any information about classes and fields, and any queries for classes defined by the schema will fail.
- See Also:
Realm
,RealmSchema
-
-
Nested Class Summary
Nested Classes Modifier and Type Class Description static class
DynamicRealm.Callback
The Callback used when reporting back the result of loading a Realm asynchronously using eitherRealm.getInstanceAsync(RealmConfiguration, Realm.Callback)
orgetInstanceAsync(RealmConfiguration, DynamicRealm.Callback)
.static interface
DynamicRealm.Transaction
Encapsulates a Realm transaction.
-
Field Summary
Fields Modifier and Type Field Description static io.realm.BaseRealm.ThreadLocalRealmObjectContext
objectContext
io.realm.internal.OsSharedRealm
sharedRealm
static io.realm.internal.async.RealmThreadPoolExecutor
WRITE_EXECUTOR
Thread pool executor used for write operations - only one thread is needed as writes cannot be parallelized.
-
Method Summary
All Methods Static Methods Instance Methods Concrete Methods Deprecated Methods Modifier and Type Method Description void
addChangeListener(RealmChangeListener<DynamicRealm> listener)
Adds a change listener to the Realm.Flowable<DynamicRealm>
asFlowable()
Returns an RxJava Flowable that monitors changes to this Realm.void
beginTransaction()
Starts a transaction which must be closed byBaseRealm.commitTransaction()
or aborted byBaseRealm.cancelTransaction()
.void
cancelTransaction()
Reverts all writes (created, updated, or deleted objects) made in the current write transaction and end the transaction.void
close()
Closes the Realm instance and all its resources.void
commitTransaction()
All changes sinceBaseRealm.beginTransaction()
are persisted to disk and the Realm reverts back to being read-only.DynamicRealmObject
createEmbeddedObject(String className, DynamicRealmObject parentObject, String parentProperty)
Instantiates and adds a new embedded object to the Realm.DynamicRealmObject
createObject(String className)
Instantiates and adds a new object to the Realm.DynamicRealmObject
createObject(String className, Object primaryKeyValue)
Creates an object with a given primary key.void
delete(String className)
Deletes all objects of the specified class from the Realm.void
deleteAll()
Deletes all objects from this Realm.void
executeTransaction(DynamicRealm.Transaction transaction)
Executes a given transaction on the DynamicRealm.RealmAsyncTask
executeTransactionAsync(DynamicRealm.Transaction transaction)
Similar toexecuteTransaction(Transaction)
but runs asynchronously on a worker thread.RealmAsyncTask
executeTransactionAsync(DynamicRealm.Transaction transaction, DynamicRealm.Transaction.OnError onError)
Similar toexecuteTransactionAsync(Transaction)
, but also accepts an OnError callback.RealmAsyncTask
executeTransactionAsync(DynamicRealm.Transaction transaction, DynamicRealm.Transaction.OnSuccess onSuccess)
Similar toexecuteTransactionAsync(Transaction)
, but also accepts an OnSuccess callback.RealmAsyncTask
executeTransactionAsync(DynamicRealm.Transaction transaction, DynamicRealm.Transaction.OnSuccess onSuccess, DynamicRealm.Transaction.OnError onError)
Similar toexecuteTransactionAsync(Transaction)
, but also accepts an OnSuccess and OnError callbacks.DynamicRealm
freeze()
Returns a frozen snapshot of the current Realm.RealmConfiguration
getConfiguration()
Returns theRealmConfiguration
for this Realm.static DynamicRealm
getInstance(RealmConfiguration configuration)
Realm static constructor that returns a dynamic variant of the Realm instance defined by providedRealmConfiguration
.static RealmAsyncTask
getInstanceAsync(RealmConfiguration configuration, DynamicRealm.Callback callback)
The creation of the first Realm instance perRealmConfiguration
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).long
getNumberOfActiveVersions()
Returns the current number of active versions currently being held by this Realm.String
getPath()
Returns the canonical path to where this Realm is persisted on disk.RealmSchema
getSchema()
Returns the mutable schema for this Realm.SubscriptionSet
getSubscriptions()
Returns the subscription set associated with this Realm.long
getVersion()
Returns the schema version for this Realm.boolean
isAutoRefresh()
Retrieves the auto-refresh status of the Realm instance.boolean
isClosed()
Checks if theRealm
instance has already been closed.boolean
isEmpty()
Checks if thisRealm
contains any objects.boolean
isFrozen()
Returns whether or not this Realm is frozen.boolean
isInTransaction()
Checks if the Realm is currently in a transaction.void
refresh()
Refreshes the Realm instance and all the RealmResults and RealmObjects instances coming from it.void
removeAllChangeListeners()
Removes all user-defined change listeners.void
removeChangeListener(RealmChangeListener<DynamicRealm> listener)
Removes the specified change listener.void
setAutoRefresh(boolean autoRefresh)
Sets the auto-refresh status of the Realm instance.void
stopWaitForChange()
Deprecated.this method will be removed in the next-major releaseboolean
waitForChange()
Deprecated.this method will be removed on the next-major release.RealmQuery<DynamicRealmObject>
where(String className)
Returns a RealmQuery, which can be used to query the provided class.void
writeCopyTo(File destination)
Writes a compacted copy of the Realm to the given destination File.void
writeEncryptedCopyTo(File destination, byte[] key)
Writes a compacted and encrypted copy of the Realm to the given destination File.
-
-
-
Field Detail
-
WRITE_EXECUTOR
public static final io.realm.internal.async.RealmThreadPoolExecutor WRITE_EXECUTOR
Thread pool executor used for write operations - only one thread is needed as writes cannot be parallelized.
-
sharedRealm
public io.realm.internal.OsSharedRealm sharedRealm
-
objectContext
public static final io.realm.BaseRealm.ThreadLocalRealmObjectContext objectContext
-
-
Method Detail
-
getInstance
public static DynamicRealm getInstance(RealmConfiguration configuration)
Realm static constructor that returns a dynamic variant of the Realm instance defined by providedRealmConfiguration
. Dynamic Realms do not care about schemaVersion and schemas, so opening a DynamicRealm will never trigger a migration.- Returns:
- the DynamicRealm defined by the configuration.
- Throws:
RealmFileException
- if an error happened when accessing the underlying Realm file.IllegalArgumentException
- ifconfiguration
argument isnull
.- See Also:
for details on how to configure a Realm.
-
getInstanceAsync
public static RealmAsyncTask getInstanceAsync(RealmConfiguration configuration, DynamicRealm.Callback callback)
The creation of the first Realm instance perRealmConfiguration
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:
configuration
-RealmConfiguration
used to open the Realm.callback
- invoked to return the results.- Returns:
- a
RealmAsyncTask
representing a cancellable task. - Throws:
IllegalArgumentException
- if a nullRealmConfiguration
or a nullDynamicRealm.Callback
is provided.IllegalStateException
- if it is called from a non-Looper orIntentService
thread.- See Also:
for more details.
-
createObject
public DynamicRealmObject createObject(String className)
Instantiates and adds a new object to the Realm.- Parameters:
className
- the class name of the object to create.- Returns:
- the new object.
- Throws:
RealmException
- if the object could not be created.
-
createObject
public DynamicRealmObject createObject(String className, Object primaryKeyValue)
Creates an object with a given primary key. Classes without a primary key defined must usecreateObject(String)
} instead.- Returns:
- the new object. All fields will have default values for their type, except for the primary key field which will have the provided value.
- Throws:
RealmException
- if object could not be created due to the primary key being invalid.IllegalStateException
- if the model clazz does not have an primary key defined.IllegalArgumentException
- if theprimaryKeyValue
doesn't have a value that can be converted to the expected value.
-
createEmbeddedObject
public DynamicRealmObject createEmbeddedObject(String className, DynamicRealmObject parentObject, String parentProperty)
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:
className
- the class name of the object to create.parentObject
- The parent object which should hold a reference to the embedded object. If the parent property is a list the embedded object will be added to the end of that list.parentProperty
- the property in the parent class which holds the reference.- Returns:
- the newly created embedded object.
- Throws:
IllegalArgumentException
- ifclazz
is not an embedded class or if the property in the parent class cannot hold objects of the appropriate type.- See Also:
RealmClass.embedded()
-
where
public RealmQuery<DynamicRealmObject> where(String className)
Returns a RealmQuery, which can be used to query the provided class.- Parameters:
className
- the class of the object which is to be queried.- Returns:
- a RealmQuery, which can be used to query for specific objects of provided type.
- Throws:
IllegalArgumentException
- if the class doesn't exist.- See Also:
RealmQuery
-
addChangeListener
public void addChangeListener(RealmChangeListener<DynamicRealm> listener)
Adds a change listener to the Realm.The listeners will be executed when changes are committed by this or another thread.
Realm instances are cached per thread. For that reason it is important to remember to remove listeners again either using
removeChangeListener(RealmChangeListener)
orremoveAllChangeListeners()
. Not doing so can cause memory leaks.- Parameters:
listener
- the change listener.- Throws:
IllegalArgumentException
- if the change listener isnull
.- See Also:
RealmChangeListener
,removeChangeListener(RealmChangeListener)
,removeAllChangeListeners()
,refresh()
-
removeChangeListener
public void removeChangeListener(RealmChangeListener<DynamicRealm> listener)
Removes the specified change listener.- Parameters:
listener
- the change listener to be removed.- Throws:
IllegalArgumentException
- if the change listener isnull
.IllegalStateException
- if you try to remove a listener from a non-Looper Thread.- See Also:
RealmChangeListener
-
removeAllChangeListeners
public void removeAllChangeListeners()
Removes all user-defined change listeners.- Throws:
IllegalStateException
- if you try to remove listeners from a non-Looper Thread.- See Also:
RealmChangeListener
-
delete
public void delete(String className)
Deletes all objects of the specified class from the Realm.- Parameters:
className
- the class for which all objects should be removed.- Throws:
IllegalStateException
- if the Realm is closed or called from an incorrect thread.
-
executeTransaction
public void executeTransaction(DynamicRealm.Transaction transaction)
Executes a given transaction on the DynamicRealm.beginTransaction()
andcommitTransaction()
will be called automatically. If any exception is thrown during the transactioncancelTransaction()
will be called instead ofcommitTransaction()
.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 usingexecuteTransactionAsync(Transaction)
instead.- Parameters:
transaction
-DynamicRealm.Transaction
to execute.- Throws:
IllegalArgumentException
- if thetransaction
isnull
.RealmException
- if called from the UI thread, unless an explicit opt-in has been declared inRealmConfiguration.Builder.allowWritesOnUiThread(boolean)
.
-
executeTransactionAsync
public RealmAsyncTask executeTransactionAsync(DynamicRealm.Transaction transaction)
Similar toexecuteTransaction(Transaction)
but runs asynchronously on a worker thread.- Parameters:
transaction
-DynamicRealm.Transaction
to execute.- Returns:
- a
RealmAsyncTask
representing a cancellable task. - Throws:
IllegalArgumentException
- if thetransaction
isnull
, or if the Realm is opened from another thread.
-
executeTransactionAsync
public RealmAsyncTask executeTransactionAsync(DynamicRealm.Transaction transaction, DynamicRealm.Transaction.OnSuccess onSuccess)
Similar toexecuteTransactionAsync(Transaction)
, but also accepts an OnSuccess callback.- Parameters:
transaction
-DynamicRealm.Transaction
to execute.onSuccess
- callback invoked when the transaction succeeds.- Returns:
- a
RealmAsyncTask
representing a cancellable task. - Throws:
IllegalArgumentException
- if thetransaction
isnull
, or if the realm is opened from another thread.
-
executeTransactionAsync
public RealmAsyncTask executeTransactionAsync(DynamicRealm.Transaction transaction, DynamicRealm.Transaction.OnError onError)
Similar toexecuteTransactionAsync(Transaction)
, but also accepts an OnError callback.- Parameters:
transaction
-DynamicRealm.Transaction
to execute.onError
- callback invoked when the transaction fails.- Returns:
- a
RealmAsyncTask
representing a cancellable task. - Throws:
IllegalArgumentException
- if thetransaction
isnull
, or if the realm is opened from another thread.
-
executeTransactionAsync
public RealmAsyncTask executeTransactionAsync(DynamicRealm.Transaction transaction, @Nullable DynamicRealm.Transaction.OnSuccess onSuccess, @Nullable DynamicRealm.Transaction.OnError onError)
Similar toexecuteTransactionAsync(Transaction)
, but also accepts an OnSuccess and OnError callbacks.- Parameters:
transaction
-DynamicRealm.Transaction
to execute.onSuccess
- callback invoked when the transaction succeeds.onError
- callback invoked when the transaction fails.- Returns:
- a
RealmAsyncTask
representing a cancellable task. - Throws:
IllegalArgumentException
- if thetransaction
isnull
, or if the realm is opened from another thread.
-
asFlowable
public Flowable<DynamicRealm> 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 -onComplete
will never be called.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:
realm.asFlowable() .observeOn(Schedulers.computation()) .map(rxRealm -> doExpensiveWork(rxRealm)) .observeOn(AndroidSchedulers.mainThread()) .subscribe( ... );
If you would like the
asFlowable()
to stop emitting items, you can instruct RxJava to only emit only the first item by using thefirst()
operator:realm.asFlowable().first().subscribe( ... ); // You only get the results once
- Returns:
- RxJava Observable that only calls
onNext
. It will never callonComplete
orOnError
. - See Also:
- RxJava and Realm
-
isEmpty
public boolean isEmpty()
Checks if thisRealm
contains any objects.- Returns:
true
if empty, @{code false} otherwise.
-
getSchema
public RealmSchema getSchema()
Returns the mutable schema for this Realm.- Returns:
- The
RealmSchema
for this Realm.
-
freeze
public DynamicRealm freeze()
Returns a frozen snapshot of the current Realm. This Realm can be read and queried from any thread without throwing anIllegalStateException
. A frozen Realm has its own lifecycle and can be closed by callingCloseable.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.
-
setAutoRefresh
public void setAutoRefresh(boolean autoRefresh)
Sets the auto-refresh status of the Realm instance.Auto-refresh is a feature that enables automatic update of the current Realm instance and all its derived objects (RealmResults and RealmObject instances) when a commit is performed on a Realm acting on the same file in another thread. This feature is only available if the Realm instance lives on a
Looper
enabled thread.- Parameters:
autoRefresh
-true
will turn auto-refresh on,false
will turn it off.- Throws:
IllegalStateException
- if called from a non-Looper thread.
-
isAutoRefresh
public boolean isAutoRefresh()
Retrieves the auto-refresh status of the Realm instance.- Returns:
- the auto-refresh status.
-
refresh
public void refresh()
Refreshes the Realm instance and all the RealmResults and RealmObjects instances coming from it. It also calls any listeners associated with the Realm if needed.WARNING: Calling this on a thread with async queries will turn those queries into synchronous queries. This means this method will throw a
RealmException
ifRealmConfiguration.Builder.allowQueriesOnUiThread(boolean)
was used withtrue
to obtain a Realm instance. In most cases it is better to useRealmChangeListener
s to be notified about changes to the Realm on a given thread than it is to use this method.- Throws:
IllegalStateException
- if attempting to refresh from within a transaction.RealmException
- if called from the UI thread after opting out viaRealmConfiguration.Builder.allowQueriesOnUiThread(boolean)
.
-
isInTransaction
public boolean isInTransaction()
Checks if the Realm is currently in a transaction.- Returns:
true
if inside a transaction,false
otherwise.
-
writeCopyTo
public void writeCopyTo(File destination)
Writes a compacted copy of the Realm to the given destination File. The resulting file can be used as initial dataset to bootstrap a local or synced Realm in other devices.The destination file cannot already exist.
Note that if this is called from within a transaction it writes the current data, and not the data as it was when the last transaction was committed.
- Parameters:
destination
- file to save the Realm to.- Throws:
IllegalArgumentException
- if destination argument is null.RealmFileException
- if an error happened when accessing the underlying Realm file or writing to the destination file.IllegalStateException
- if called from the UI thread.IllegalStateException
- if not all client changes are integrated in server.
-
writeEncryptedCopyTo
public void writeEncryptedCopyTo(File destination, byte[] key)
Writes a compacted and encrypted copy of the Realm to the given destination File. The resulting file can be used as initial dataset to bootstrap a local or synced Realm in other devices.The destination file cannot already exist.
Note that if this is called from within a transaction it writes the current data, and not the data as it was when the last transaction was committed.
- Parameters:
destination
- file to save the Realm to.key
- a 64-byte encryption key.- Throws:
IllegalArgumentException
- if destination argument is null.RealmFileException
- if an error happened when accessing the underlying Realm file or writing to the destination file.IllegalStateException
- if called from the UI thread.IllegalStateException
- if not all client changes are integrated in server.
-
waitForChange
@Deprecated public boolean waitForChange()
Deprecated.this method will be removed on the next-major release.Blocks the current thread until new changes to the Realm are available orstopWaitForChange()
is called from another thread. Once stopWaitForChange is called, all future calls to this method will return false immediately.- Returns:
true
if the Realm was updated to the latest version,false
if it was cancelled by calling stopWaitForChange.- Throws:
IllegalStateException
- if calling this from within a transaction or from a Looper thread.RealmMigrationNeededException
- on typedRealm
if the latest version contains incompatible schema changes.
-
stopWaitForChange
@Deprecated public void stopWaitForChange()
Deprecated.this method will be removed in the next-major releaseMakes any currentwaitForChange()
returnfalse
immediately. Once this is called, all future calls to waitForChange will immediately returnfalse
.This method is thread-safe and should _only_ be called from another thread than the one that called waitForChange.
- Throws:
IllegalStateException
- if theRealm
instance has already been closed.
-
beginTransaction
public void beginTransaction()
Starts a transaction which must be closed byBaseRealm.commitTransaction()
or aborted byBaseRealm.cancelTransaction()
. Transactions are used to atomically create, update and delete objects within a Realm.Before beginning a transaction, the Realm instance is updated to the latest version in order to include all changes from other threads. This update does not trigger any registered
RealmChangeListener
.It is therefore recommended to query for the items that should be modified from inside the transaction. Otherwise there is a risk that some of the results have been deleted or modified when the transaction begins.
// Don't do this RealmResults<Person> persons = realm.where(Person.class).findAll(); realm.beginTransaction(); persons.first().setName("John"); realm.commitTransaction(); // Do this instead realm.beginTransaction(); RealmResults<Person> persons = realm.where(Person.class).findAll(); persons.first().setName("John"); realm.commitTransaction();
Notice: it is not possible to nest transactions. If you start a transaction within a transaction an exception is thrown.
- Throws:
RealmMigrationNeededException
- on typedRealm
if the latest version contains incompatible schema changes.
-
commitTransaction
public void commitTransaction()
All changes sinceBaseRealm.beginTransaction()
are persisted to disk and the Realm reverts back to being read-only. An event is sent to notify all other Realm instances that a change has occurred. When the event is received, the other Realms will update their objects andRealmResults
to reflect the changes from this commit.
-
cancelTransaction
public void cancelTransaction()
Reverts all writes (created, updated, or deleted objects) made in the current write transaction and end the transaction.The Realm reverts back to read-only.
Calling this when not in a transaction will throw an exception.
-
isFrozen
public boolean isFrozen()
Returns whether or not this Realm is frozen.- Returns:
true
if the Realm is frozen,false
if it is not.- See Also:
freeze()
-
getNumberOfActiveVersions
public long getNumberOfActiveVersions()
Returns the current number of active versions currently being held by this Realm.Having a large number of active versions have a negative impact on the size of the Realm file. See the FAQ for more information.
- Returns:
- number of active versions currently being held by the Realm.
- See Also:
RealmConfiguration.Builder.maxNumberOfActiveVersions(long)
-
getPath
public String getPath()
Returns the canonical path to where this Realm is persisted on disk.- Returns:
- the canonical path to the Realm file.
- See Also:
File.getCanonicalPath()
-
getConfiguration
public RealmConfiguration getConfiguration()
Returns theRealmConfiguration
for this Realm.- Returns:
- the
RealmConfiguration
for this Realm.
-
getVersion
public long getVersion()
Returns the schema version for this Realm.- Returns:
- the schema version for the Realm file backing this Realm.
-
close
public void close()
Closes the Realm instance and all its resources.It's important to always remember to close Realm instances when you're done with it in order not to leak memory, file descriptors or grow the size of Realm file out of measure.
- Specified by:
close
in interfaceAutoCloseable
- Specified by:
close
in interfaceCloseable
- Throws:
IllegalStateException
- if attempting to close from another thread.
-
isClosed
public boolean isClosed()
Checks if theRealm
instance has already been closed.- Returns:
true
if closed,false
otherwise.- Throws:
IllegalStateException
- if attempting to close from another thread.
-
getSubscriptions
public SubscriptionSet getSubscriptions()
Returns the subscription set associated with this Realm. The subscription set defines a set of queries that define which data is synchronized between this realm and the server.This method is only applicable to synchronized realms using flexible sync.
- Returns:
- the subscription set associated with this realm.
- Throws:
IllegalStateException
- if this realm is either a local realm or a partion-based synchronized realm.
-
deleteAll
public void deleteAll()
Deletes all objects from this Realm.- Throws:
IllegalStateException
- if the Realm is closed or called from an incorrect thread.
-
-