public class DynamicRealm extends Object
Realm
. 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 the RealmConfiguration
.
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.
Realm
,
RealmSchema
Modifier and Type | Class and Description |
---|---|
static class |
io.realm.BaseRealm.InstanceCallback<T extends io.realm.BaseRealm>
The Callback used when reporting back the result of loading a Realm asynchronously using either
Realm.getInstanceAsync(RealmConfiguration, Realm.Callback) or
getInstanceAsync(RealmConfiguration, DynamicRealm.Callback) . |
static class |
io.realm.BaseRealm.RealmObjectContext |
static class |
DynamicRealm.Callback
The Callback used when reporting back the result of loading a Realm asynchronously using either
Realm.getInstanceAsync(RealmConfiguration, Realm.Callback) or
getInstanceAsync(RealmConfiguration, DynamicRealm.Callback) . |
static interface |
DynamicRealm.Transaction
Encapsulates a Realm transaction.
|
Modifier and Type | Field and Description |
---|---|
static io.realm.BaseRealm.ThreadLocalRealmObjectContext |
objectContext |
SharedRealm |
sharedRealm |
Modifier and Type | Method and Description |
---|---|
void |
addChangeListener(RealmChangeListener<DynamicRealm> listener)
Adds a change listener to the Realm.
|
<any> |
asFlowable()
Returns an RxJava Flowable that monitors changes to this Realm.
|
void |
beginTransaction()
Starts a transaction which must be closed by
BaseRealm.commitTransaction() or aborted by
BaseRealm.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 since
BaseRealm.beginTransaction() are persisted to disk and the Realm reverts back to
being read-only. |
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.
|
RealmConfiguration |
getConfiguration()
Returns the
RealmConfiguration for this Realm. |
static DynamicRealm |
getInstance(RealmConfiguration configuration)
Realm static constructor that returns a dynamic variant of the Realm instance defined by provided
RealmConfiguration . |
static RealmAsyncTask |
getInstanceAsync(RealmConfiguration configuration,
DynamicRealm.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). |
String |
getPath()
Returns the canonical path to where this Realm is persisted on disk.
|
RealmSchema |
getSchema()
Returns the mutable schema for 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 the
Realm instance has already been closed. |
boolean |
isEmpty()
Checks if this
Realm contains any objects. |
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()
Makes any current
waitForChange() return false immediately. |
boolean |
waitForChange()
Blocks the current thread until new changes to the Realm are available or
stopWaitForChange()
is called from another thread. |
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.
|
public SharedRealm sharedRealm
public static final io.realm.BaseRealm.ThreadLocalRealmObjectContext objectContext
public static DynamicRealm getInstance(RealmConfiguration configuration)
RealmConfiguration
. Dynamic Realms do not care about schemaVersion and schemas, so opening a
DynamicRealm will never trigger a migration.RealmFileException
- if an error happened when accessing the underlying Realm file.IllegalArgumentException
- if configuration
argument is null
.for details on how to configure a Realm.
public static RealmAsyncTask getInstanceAsync(RealmConfiguration configuration, DynamicRealm.Callback callback)
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.configuration
- RealmConfiguration
used to open the Realm.callback
- invoked to return the results.RealmAsyncTask
representing a cancellable task.IllegalArgumentException
- if a null RealmConfiguration
or a null DynamicRealm.Callback
is provided.IllegalStateException
- if it is called from a non-Looper or IntentService
thread.for more details.
public DynamicRealmObject createObject(String className)
className
- the class name of the object to create.RealmException
- if the object could not be created.public DynamicRealmObject createObject(String className, Object primaryKeyValue)
createObject(String)
} instead.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 the primaryKeyValue
doesn't have a value that can be converted to the
expected value.public RealmQuery<DynamicRealmObject> where(String className)
className
- the class of the object which is to be queried.IllegalArgumentException
- if the class doesn't exist.RealmQuery
public void addChangeListener(RealmChangeListener<DynamicRealm> listener)
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)
or removeAllChangeListeners()
. Not doing so can cause memory leaks.
listener
- the change listener.IllegalArgumentException
- if the change listener is null
.RealmChangeListener
,
removeChangeListener(RealmChangeListener)
,
removeAllChangeListeners()
,
waitForChange()
public void removeChangeListener(RealmChangeListener<DynamicRealm> listener)
listener
- the change listener to be removed.IllegalArgumentException
- if the change listener is null
.IllegalStateException
- if you try to remove a listener from a non-Looper Thread.RealmChangeListener
public void removeAllChangeListeners()
IllegalStateException
- if you try to remove listeners from a non-Looper Thread.RealmChangeListener
public void delete(String className)
className
- the class for which all objects should be removed.public void executeTransaction(DynamicRealm.Transaction transaction)
beginTransaction()
and
commitTransaction()
will be called automatically. If any exception is thrown
during the transaction cancelTransaction()
will be called instead of commitTransaction()
.transaction
- DynamicRealm.Transaction
to execute.IllegalArgumentException
- if the transaction
is null
.public <any> asFlowable()
onComplete
will never be called.
If you would like the asFlowable()
to stop emitting items, you can instruct RxJava to
only emit only the first item by using the first()
operator:
realm.asFlowable().first().subscribe( ... ) // You only get the results once
onNext
. It will never call onComplete
or OnError
.public RealmSchema getSchema()
RealmSchema
for this Realm.public void setAutoRefresh(boolean autoRefresh)
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.
autoRefresh
- true
will turn auto-refresh on, false
will turn it off.IllegalStateException
- if called from a non-Looper thread.public boolean isAutoRefresh()
public void refresh()
WARNING: Calling this on a thread with async queries will turn those queries into synchronous queries.
In most cases it is better to use RealmChangeListener
s to be notified about changes to the
Realm on a given thread than it is to use this method.
IllegalStateException
- if attempting to refresh from within a transaction.public boolean isInTransaction()
true
if inside a transaction, false
otherwise.public void writeCopyTo(File destination)
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.
destination
- file to save the Realm to.RealmFileException
- if an error happened when accessing the underlying Realm file or writing to the
destination file.public void writeEncryptedCopyTo(File destination, byte[] key)
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.
destination
- file to save the Realm to.key
- a 64-byte encryption key.IllegalArgumentException
- if destination argument is null.RealmFileException
- if an error happened when accessing the underlying Realm file or writing to the
destination file.public boolean waitForChange()
stopWaitForChange()
is called from another thread. Once stopWaitForChange is called, all future calls to this method will
return false immediately.true
if the Realm was updated to the latest version, false
if it was
cancelled by calling stopWaitForChange.IllegalStateException
- if calling this from within a transaction or from a Looper thread.RealmMigrationNeededException
- on typed Realm
if the latest version contains
incompatible schema changes.public void stopWaitForChange()
waitForChange()
return false
immediately. Once this is called,
all future calls to waitForChange will immediately return false
.
This method is thread-safe and should _only_ be called from another thread than the one that called waitForChange.
IllegalStateException
- if the Realm
instance has already been closed.public void beginTransaction()
BaseRealm.commitTransaction()
or aborted by
BaseRealm.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.
RealmMigrationNeededException
- on typed Realm
if the latest version contains
incompatible schema changes.public void commitTransaction()
BaseRealm.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 and RealmResults
to reflect the
changes from this commit.public void cancelTransaction()
The Realm reverts back to read-only.
Calling this when not in a transaction will throw an exception.
public String getPath()
File.getCanonicalPath()
public RealmConfiguration getConfiguration()
RealmConfiguration
for this Realm.RealmConfiguration
for this Realm.public long getVersion()
public void close()
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.
close
in interface Closeable
close
in interface AutoCloseable
IllegalStateException
- if attempting to close from another thread.public boolean isClosed()
Realm
instance has already been closed.true
if closed, false
otherwise.IllegalStateException
- if attempting to close from another thread.public boolean isEmpty()
Realm
contains any objects.true
if empty, @{code false} otherwise.public void deleteAll()
IllegalStateException
- if the corresponding Realm is closed or called from an incorrect thread.