public class Realm extends Object
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 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 Handler
mechanism. This also means
that Realm instances on threads without a Looper
cannot receive updates unless waitForChange()
is manually called.
A standard pattern for working with Realm in Android activities can be seen below:
public class RealmApplication extends Application { \@Override 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; \@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.layout_main); realm = Realm.getDefaultInstance(); } \@Override protected void onDestroy() { super.onDestroy(); realm.close(); } }
Realm supports String and byte fields containing up to 16 MB.
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
getInstanceAsync(RealmConfiguration, Realm.Callback) or
DynamicRealm.getInstanceAsync(RealmConfiguration, DynamicRealm.Callback) . |
static class |
io.realm.BaseRealm.RealmObjectContext |
static class |
Realm.Callback
The Callback used when reporting back the result of loading a Realm asynchronously using either
getInstanceAsync(RealmConfiguration, Realm.Callback) or
DynamicRealm.getInstanceAsync(RealmConfiguration, DynamicRealm.Callback) . |
static interface |
Realm.Transaction
Encapsulates a Realm transaction.
|
static interface |
Realm.UnsubscribeCallback
Interface used when canceling query-based sync subscriptions.
|
Modifier and Type | Field and Description |
---|---|
static String |
DEFAULT_REALM_NAME |
static io.realm.BaseRealm.ThreadLocalRealmObjectContext |
objectContext |
OsSharedRealm |
sharedRealm |
Modifier and Type | Method and Description |
---|---|
void |
addChangeListener(RealmChangeListener<Realm> 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. |
static boolean |
compactRealm(RealmConfiguration configuration)
Compacts a Realm file.
|
<E extends RealmModel> |
copyFromRealm(E realmObject)
Makes an unmanaged in-memory copy of an already persisted
RealmObject . |
<E extends RealmModel> |
copyFromRealm(E realmObject,
int maxDepth)
Makes an unmanaged in-memory copy of an already persisted
RealmObject . |
<E extends RealmModel> |
copyFromRealm(Iterable<E> realmObjects)
Makes an unmanaged in-memory copy of already persisted RealmObjects.
|
<E extends RealmModel> |
copyFromRealm(Iterable<E> realmObjects,
int maxDepth)
Makes an unmanaged in-memory copy of already persisted RealmObjects.
|
<E extends RealmModel> |
copyToRealm(E object,
ImportFlag... flags)
Copies a RealmObject to the Realm instance and returns the copy.
|
<E extends RealmModel> |
copyToRealm(Iterable<E> objects,
ImportFlag... flags)
Copies a collection of RealmObjects to the Realm instance and returns their copy.
|
<E extends RealmModel> |
copyToRealmOrUpdate(E object,
ImportFlag... flags)
Updates an existing RealmObject that is identified by the same
PrimaryKey or creates
a new copy if no existing object could be found. |
<E extends RealmModel> |
copyToRealmOrUpdate(Iterable<E> objects,
ImportFlag... flags)
Updates a list of existing RealmObjects that is identified by their
PrimaryKey or
creates a new copy if no existing object could be found. |
<E extends RealmModel> |
createAllFromJson(Class<E> clazz,
InputStream inputStream)
Creates a Realm object for each object in a JSON array.
|
<E extends RealmModel> |
createAllFromJson(Class<E> clazz,
org.json.JSONArray json)
Creates a Realm object for each object in a JSON array.
|
<E extends RealmModel> |
createAllFromJson(Class<E> clazz,
String json)
Creates a Realm object for each object in a JSON array.
|
<E extends RealmModel> |
createObject(Class<E> clazz)
Instantiates and adds a new object to the Realm.
|
<E extends RealmModel> |
createObject(Class<E> clazz,
Object primaryKeyValue)
Instantiates and adds a new object to the Realm with the primary key value already set.
|
<E extends RealmModel> |
createObjectFromJson(Class<E> clazz,
InputStream inputStream)
Creates a Realm object pre-filled with data from a JSON object.
|
<E extends RealmModel> |
createObjectFromJson(Class<E> clazz,
org.json.JSONObject json)
Creates a Realm object pre-filled with data from a JSON object.
|
<E extends RealmModel> |
createObjectFromJson(Class<E> clazz,
String json)
Creates a Realm object pre-filled with data from a JSON object.
|
<E extends RealmModel> |
createOrUpdateAllFromJson(Class<E> clazz,
InputStream in)
Tries to update a list of existing objects identified by their primary key with new JSON data.
|
<E extends RealmModel> |
createOrUpdateAllFromJson(Class<E> clazz,
org.json.JSONArray json)
Tries to update a list of existing objects identified by their primary key with new JSON data.
|
<E extends RealmModel> |
createOrUpdateAllFromJson(Class<E> clazz,
String json)
Tries to update a list of existing objects identified by their primary key with new JSON data.
|
<E extends RealmModel> |
createOrUpdateObjectFromJson(Class<E> clazz,
InputStream in)
Tries to update an existing object defined by its primary key with new JSON data.
|
<E extends RealmModel> |
createOrUpdateObjectFromJson(Class<E> clazz,
org.json.JSONObject json)
Tries to update an existing object defined by its primary key with new JSON data.
|
<E extends RealmModel> |
createOrUpdateObjectFromJson(Class<E> clazz,
String json)
Tries to update an existing object defined by its primary key with new JSON data.
|
void |
delete(Class<? extends RealmModel> clazz)
Deletes all objects of the specified class from the Realm.
|
void |
deleteAll()
Deletes all objects from this Realm.
|
static boolean |
deleteRealm(RealmConfiguration configuration)
Deletes the Realm file along with the related temporary files specified by the given
RealmConfiguration
from the filesystem. |
void |
executeTransaction(Realm.Transaction transaction)
Executes a given transaction on the Realm.
|
RealmAsyncTask |
executeTransactionAsync(Realm.Transaction transaction)
Similar to
executeTransaction(Transaction) but runs asynchronously on a worker thread. |
RealmAsyncTask |
executeTransactionAsync(Realm.Transaction transaction,
Realm.Transaction.OnError onError)
Similar to
executeTransactionAsync(Transaction) , but also accepts an OnError callback. |
RealmAsyncTask |
executeTransactionAsync(Realm.Transaction transaction,
Realm.Transaction.OnSuccess onSuccess)
Similar to
executeTransactionAsync(Transaction) , but also accepts an OnSuccess callback. |
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. |
RealmConfiguration |
getConfiguration()
Returns the
RealmConfiguration for this Realm. |
static RealmConfiguration |
getDefaultConfiguration()
Returns the default configuration for
getDefaultInstance() . |
static Realm |
getDefaultInstance()
Realm static constructor that returns the Realm instance defined by the
RealmConfiguration set
by setDefaultConfiguration(RealmConfiguration) |
static Object |
getDefaultModule()
Returns the default Realm module.
|
static int |
getGlobalInstanceCount(RealmConfiguration configuration)
Returns the current number of open Realm instances across all threads in current process that are using this
configuration.
|
static Realm |
getInstance(RealmConfiguration configuration)
Realm static constructor that returns the Realm instance defined by provided
RealmConfiguration |
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). |
static int |
getLocalInstanceCount(RealmConfiguration configuration)
Returns the current number of open Realm instances on the thread calling this method.
|
String |
getPath()
Returns the canonical path to where this Realm is persisted on disk.
|
RealmPermissions |
getPermissions()
Returns all permissions associated with the current Realm.
|
ClassPermissions |
getPermissions(Class<? extends RealmModel> clazz)
Returns all permissions associated with the given class.
|
RealmPrivileges |
getPrivileges()
Returns the privileges granted to the current user for this Realm.
|
ClassPrivileges |
getPrivileges(Class<? extends RealmModel> clazz)
Returns the privileges granted the current user for the given class.
|
ObjectPrivileges |
getPrivileges(RealmModel object)
Returns the privileges granted to the current user for the given object.
|
RealmResults<Role> |
getRoles()
Returns all
Role objects available in this Realm. |
RealmSchema |
getSchema()
Returns the schema for this Realm.
|
Subscription |
getSubscription(String name)
Returns the first subscription that matches the given name.
|
RealmResults<Subscription> |
getSubscriptions()
Returns a list of all known subscriptions, regardless of their status.
|
RealmResults<Subscription> |
getSubscriptions(String pattern)
Returns a list of all subscriptions that match a given pattern.
|
long |
getVersion()
Returns the schema version for this Realm.
|
static void |
init(android.content.Context context)
Initializes the Realm library and creates a default configuration that is ready to use.
|
static void |
init(android.content.Context context,
String userAgent)
Initializes the Realm library and creates a default configuration that is ready to use.
|
void |
insert(Collection<? extends RealmModel> objects)
Inserts a list of an unmanaged RealmObjects.
|
void |
insert(RealmModel object)
Inserts an unmanaged RealmObject.
|
void |
insertOrUpdate(Collection<? extends RealmModel> objects)
Inserts or updates a list of unmanaged RealmObjects.
|
void |
insertOrUpdate(RealmModel object)
Inserts or updates an unmanaged RealmObject.
|
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.
|
static void |
migrateRealm(RealmConfiguration configuration)
Manually triggers the migration associated with a given RealmConfiguration.
|
static void |
migrateRealm(RealmConfiguration configuration,
RealmMigration migration)
Manually triggers a migration on a RealmMigration.
|
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<Realm> listener)
Removes the specified change listener.
|
static void |
removeDefaultConfiguration()
Removes the current default configuration (if any).
|
void |
setAutoRefresh(boolean autoRefresh)
Sets the auto-refresh status of the Realm instance.
|
static void |
setDefaultConfiguration(RealmConfiguration configuration)
Sets the
RealmConfiguration used when calling getDefaultInstance() . |
void |
stopWaitForChange()
Makes any current
waitForChange() return false immediately. |
RealmAsyncTask |
unsubscribeAsync(String subscriptionName,
Realm.UnsubscribeCallback callback)
Cancel a named subscription that was created by calling
RealmQuery.findAllAsync(String) . |
boolean |
waitForChange()
Blocks the current thread until new changes to the Realm are available or
stopWaitForChange()
is called from another thread. |
<E extends RealmModel> |
where(Class<E> clazz)
Returns a typed RealmQuery, which can be used to query for specific objects of this type
|
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 static final String DEFAULT_REALM_NAME
public OsSharedRealm sharedRealm
public static final io.realm.BaseRealm.ThreadLocalRealmObjectContext objectContext
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 boolean isEmpty()
Realm
contains any objects.true
if empty, @{code false} otherwise.public RealmSchema getSchema()
UnsupportedOperationException
.
The schema can only be modified using DynamicRealm.getSchema()
or through an migration.
RealmSchema
for this Realm.public static void init(android.content.Context context)
A good place is in an Application
subclass:
public class MyApplication extends Application {
\@Override
public void onCreate() {
super.onCreate();
Realm.init(this);
}
}
Remember to register it in the AndroidManifest.xml
file:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="io.realm.example">
<application android:name=".MyApplication">
// ...
</application>
</manifest>
context
- the Application Context.IllegalArgumentException
- if a null
context is provided.IllegalStateException
- if Context.getFilesDir()
could not be found.getDefaultInstance()
public static void init(android.content.Context context, String userAgent)
A good place is in an Application
subclass:
public class MyApplication extends Application {
\@Override
public void onCreate() {
super.onCreate();
Realm.init(this, "MyApp/" + BuildConfig.VERSION_NAME);
}
}
Remember to register it in the AndroidManifest.xml
file:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="io.realm.example">
<application android:name=".MyApplication">
// ...
</application>
</manifest>
context
- the Application Context.userAgent
- optional user defined string that will be sent to the Realm Object Server
as part of a User-Agent
header when a session is established. This setting will not be
used by non-synchronized Realms.IllegalArgumentException
- if a null
context or userAgent is provided.IllegalStateException
- if Context.getFilesDir()
could not be found.getDefaultInstance()
public static Realm getDefaultInstance()
RealmConfiguration
set
by setDefaultConfiguration(RealmConfiguration)
NullPointerException
- if no default configuration has been defined.RealmMigrationNeededException
- if no migration has been provided by the default configuration and the
RealmObject classes or version has has changed so a migration is required.RealmFileException
- if an error happened when accessing the underlying Realm file.DownloadingRealmInterruptedException
- if SyncConfiguration.Builder.waitForInitialRemoteData()
was set and the thread opening the Realm was interrupted while the download was in progress.public static Realm getInstance(RealmConfiguration configuration)
RealmConfiguration
configuration
- RealmConfiguration
used to open the RealmRealmMigrationNeededException
- if no migration has been provided by the configuration and the RealmObject
classes or version has has changed so a migration is required.RealmFileException
- if an error happened when accessing the underlying Realm file.IllegalArgumentException
- if a null RealmConfiguration
is provided.DownloadingRealmInterruptedException
- if SyncConfiguration.Builder.waitForInitialRemoteData()
was set and the thread opening the Realm was interrupted while the download was in progress.for details on how to configure a Realm.
public static RealmAsyncTask getInstanceAsync(RealmConfiguration configuration, Realm.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 Realm.Transaction.Callback
is provided.IllegalStateException
- if it is called from a non-Looper or IntentService
thread.for more details.
public static void setDefaultConfiguration(RealmConfiguration configuration)
RealmConfiguration
used when calling getDefaultInstance()
.configuration
- the RealmConfiguration
to use as the default configuration.IllegalArgumentException
- if a null RealmConfiguration
is provided.for details on how to configure a Realm.
public static RealmConfiguration getDefaultConfiguration()
getDefaultInstance()
.null
if no default configuration is specified.public static void removeDefaultConfiguration()
getDefaultInstance()
will
fail until a new default configuration has been set using setDefaultConfiguration(RealmConfiguration)
.public <E extends RealmModel> void createAllFromJson(Class<E> clazz, org.json.JSONArray json)
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.
clazz
- type of Realm objects to create.json
- an array where each JSONObject must map to the specified class.RealmException
- if mapping from JSON fails.IllegalArgumentException
- if the JSON object doesn't have a primary key property but the corresponding
RealmObjectSchema
has a PrimaryKey
defined.public <E extends RealmModel> void createOrUpdateAllFromJson(Class<E> clazz, org.json.JSONArray json)
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.
clazz
- type of RealmObject
to create or update. It must have a primary key defined.json
- array with object data.IllegalArgumentException
- if trying to update a class without a PrimaryKey
.IllegalArgumentException
- if the JSON object doesn't have a primary key property but the corresponding
RealmObjectSchema
has a PrimaryKey
defined.RealmException
- if unable to map JSON.createAllFromJson(Class, org.json.JSONArray)
public <E extends RealmModel> void createAllFromJson(Class<E> clazz, String json)
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.
clazz
- type of Realm objects to create.json
- the JSON array as a String where each object can map to the specified class.RealmException
- if mapping from JSON fails.IllegalArgumentException
- if the JSON object doesn't have a primary key property but the corresponding
RealmObjectSchema
has a PrimaryKey
defined.public <E extends RealmModel> void createOrUpdateAllFromJson(Class<E> clazz, String json)
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.
clazz
- type of RealmObject
to create or update. It must have a primary key defined.json
- string with an array of JSON objects.IllegalArgumentException
- if trying to update a class without a PrimaryKey
.RealmException
- if unable to create a JSON array from the json string.IllegalArgumentException
- if the JSON object doesn't have a primary key property but the corresponding
RealmObjectSchema
has a PrimaryKey
defined.createAllFromJson(Class, String)
public <E extends RealmModel> void createAllFromJson(Class<E> clazz, InputStream inputStream) throws IOException
RealmObject
field is not present in the
JSON object the RealmObject
field will be set to the default value for that type.
This API is only available in API level 11 or later.
This method currently does not support value list field.
clazz
- type of Realm objects created.inputStream
- the JSON array as a InputStream. All objects in the array must be of the specified class.RealmException
- if mapping from JSON fails.IllegalArgumentException
- if the JSON object doesn't have a primary key property but the corresponding
RealmObjectSchema
has a PrimaryKey
defined.IOException
- if something was wrong with the input stream.public <E extends RealmModel> void createOrUpdateAllFromJson(Class<E> clazz, InputStream in)
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 API is only available in API level 11 or later.
This method currently does not support value list field.
clazz
- type of RealmObject
to create or update. It must have a primary key defined.in
- the InputStream with a list of object data in JSON format.IllegalArgumentException
- if trying to update a class without a PrimaryKey
.IllegalArgumentException
- if the JSON object doesn't have a primary key property but the corresponding
RealmObjectSchema
has a PrimaryKey
defined.RealmException
- if unable to read JSON.createOrUpdateAllFromJson(Class, java.io.InputStream)
public <E extends RealmModel> E createObjectFromJson(Class<E> clazz, org.json.JSONObject json)
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.
clazz
- type of Realm object to create.json
- the JSONObject with object data.null
if no JSON data was provided.RealmException
- if the mapping from JSON fails.IllegalArgumentException
- if the JSON object doesn't have a primary key property but the corresponding
RealmObjectSchema
has a PrimaryKey
defined.createOrUpdateObjectFromJson(Class, org.json.JSONObject)
public <E extends RealmModel> E createOrUpdateObjectFromJson(Class<E> clazz, org.json.JSONObject json)
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.
clazz
- Type of RealmObject
to create or update. It must have a primary key defined.json
- JSONObject
with object data.RealmObject
.IllegalArgumentException
- if trying to update a class without a PrimaryKey
.IllegalArgumentException
- if the JSON object doesn't have a primary key property but the corresponding
RealmObjectSchema
has a PrimaryKey
defined.RealmException
- if JSON data cannot be mapped.createObjectFromJson(Class, org.json.JSONObject)
public <E extends RealmModel> E createObjectFromJson(Class<E> clazz, String json)
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.
clazz
- type of Realm object to create.json
- the JSON string with object data.null
if JSON string was empty or null.RealmException
- if mapping to json failed.IllegalArgumentException
- if the JSON object doesn't have a primary key property but the corresponding
RealmObjectSchema
has a PrimaryKey
defined.public <E extends RealmModel> E createOrUpdateObjectFromJson(Class<E> clazz, String json)
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.
clazz
- type of RealmObject
to create or update. It must have a primary key defined.json
- string with object data in JSON format.RealmObject
.IllegalArgumentException
- if trying to update a class without a PrimaryKey
.IllegalArgumentException
- if the JSON object doesn't have a primary key property but the corresponding
RealmObjectSchema
has a PrimaryKey
defined.RealmException
- if JSON object cannot be mapped from the string parameter.createObjectFromJson(Class, String)
public <E extends RealmModel> E createObjectFromJson(Class<E> clazz, InputStream inputStream) throws IOException
RealmObject
field is not present in the JSON
object the RealmObject
field will be set to the default value for that type.
This API is only available in API level 11 or later.
This method currently does not support value list field.
clazz
- type of Realm object to create.inputStream
- the JSON object data as a InputStream.null
if JSON string was empty or null.RealmException
- if the mapping from JSON failed.IllegalArgumentException
- if the JSON object doesn't have a primary key property but the corresponding
RealmObjectSchema
has a PrimaryKey
defined.IOException
- if something went wrong with the input stream.public <E extends RealmModel> E createOrUpdateObjectFromJson(Class<E> clazz, InputStream in)
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 API is only available in API level 11 or later.
This method currently does not support value list field.
clazz
- type of RealmObject
to create or update. It must have a primary key defined.in
- the InputStream
with object data in JSON format.RealmObject
.IllegalArgumentException
- if trying to update a class without a PrimaryKey
.IllegalArgumentException
- if the JSON object doesn't have a primary key property but the corresponding
RealmObjectSchema
has a PrimaryKey
defined.RealmException
- if failure to read JSON.createObjectFromJson(Class, java.io.InputStream)
public <E extends RealmModel> E createObject(Class<E> clazz)
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.
clazz
- the Class of the object to create.RealmException
- if the primary key is defined in the model class or an object cannot be created.createObject(Class, Object)
public <E extends RealmModel> E createObject(Class<E> clazz, Object primaryKeyValue)
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.
clazz
- the Class of the object to create.primaryKeyValue
- value for the primary key field.RealmException
- if object could not be created due to the primary key being invalid.IllegalStateException
- if the model class 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 <E extends RealmModel> E copyToRealm(E object, ImportFlag... flags)
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.
object
- the RealmObject
to copy to the Realm.flags
- any flag that modifies the behaviour of inserting the data into the Realm.IllegalArgumentException
- if the object is null
or it belongs to a Realm instance
in a different thread.public <E extends RealmModel> E copyToRealmOrUpdate(E object, ImportFlag... flags)
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.
object
- RealmObject
to copy or update.flags
- any flag that modifies the behaviour of inserting the data into the Realm.IllegalArgumentException
- if the object is null
or doesn't have a Primary key defined
or it belongs to a Realm instance in a different thread.copyToRealm(RealmModel, ImportFlag...)
public <E extends RealmModel> List<E> copyToRealm(Iterable<E> objects, ImportFlag... flags)
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.
objects
- the RealmObjects to copy to the Realm.flags
- any flag that modifies the behaviour of inserting the data into the Realm.RealmException
- if any of the objects has already been added to Realm.IllegalArgumentException
- if any of the elements in the input collection is null
.public void insert(Collection<? extends RealmModel> objects)
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:
RealmObject
for each element
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.
objects
- RealmObjects to insert.IllegalStateException
- if the corresponding Realm is closed, called from an incorrect thread or not in a
transaction.copyToRealm(Iterable, ImportFlag...)
public void insert(RealmModel object)
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:
RealmObject
for each element
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.
object
- RealmObjects to insert.IllegalStateException
- if the corresponding Realm is closed, called from an incorrect thread or not in a
transaction.RealmPrimaryKeyConstraintException
- if two objects with the same primary key is
inserted or if a primary key value already exists in the Realm.copyToRealm(RealmModel, ImportFlag...)
public void insertOrUpdate(Collection<? extends RealmModel> objects)
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:
RealmObject
for each element
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.
objects
- RealmObjects to insert.IllegalStateException
- if the corresponding Realm is closed, called from an incorrect thread or not in a
transaction.RealmPrimaryKeyConstraintException
- if two objects with the same primary key is
inserted or if a primary key value already exists in the Realm.copyToRealmOrUpdate(Iterable, ImportFlag...)
public void insertOrUpdate(RealmModel object)
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:
RealmObject
for each element
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.
object
- RealmObjects to insert.IllegalStateException
- if the corresponding Realm is closed, called from an incorrect thread or not in a
transaction.copyToRealmOrUpdate(RealmModel, ImportFlag...)
public <E extends RealmModel> List<E> copyToRealmOrUpdate(Iterable<E> objects, ImportFlag... flags)
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.
objects
- a list of objects to update or copy into Realm.flags
- any flag that modifies the behaviour of inserting the data into the Realm.IllegalArgumentException
- if RealmObject is null
or doesn't have a Primary key defined.copyToRealm(Iterable, ImportFlag...)
public <E extends RealmModel> List<E> copyFromRealm(Iterable<E> realmObjects)
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.
E
- type of object.realmObjects
- RealmObjects to copy.IllegalArgumentException
- if the RealmObject is no longer accessible or it is a DynamicRealmObject
.copyToRealmOrUpdate(Iterable, ImportFlag...)
public <E extends RealmModel> List<E> copyFromRealm(Iterable<E> realmObjects, int maxDepth)
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 null
due to maxDepth
being
reached. This can also potentially override changes made by other threads. This behaviour can be modified using
ImportFlag
s.
E
- type of object.realmObjects
- RealmObjects to copy.maxDepth
- limit of the deep copy. All references after this depth will be null
. Starting depth is
0
.IllegalArgumentException
- if maxDepth < 0
, the RealmObject is no longer accessible or it is a
DynamicRealmObject
.copyToRealmOrUpdate(Iterable, ImportFlag...)
public <E extends RealmModel> E copyFromRealm(E realmObject)
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.
E
- type of object.realmObject
- RealmObject
to copy.RealmObject
.IllegalArgumentException
- if the RealmObject is no longer accessible or it is a DynamicRealmObject
.copyToRealmOrUpdate(RealmModel, ImportFlag...)
public <E extends RealmModel> E copyFromRealm(E realmObject, int maxDepth)
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 null
due to maxDepth
being
reached. This can also potentially override changes made by other threads. This behaviour can be modified using
ImportFlag
s.
E
- type of object.realmObject
- RealmObject
to copy.maxDepth
- limit of the deep copy. All references after this depth will be null
. Starting depth is
0
.RealmObject
.IllegalArgumentException
- if maxDepth < 0
, the RealmObject is no longer accessible or it is a
DynamicRealmObject
.copyToRealmOrUpdate(RealmModel, ImportFlag...)
public <E extends RealmModel> RealmQuery<E> where(Class<E> clazz)
clazz
- the class of the object which is to be queried for.RealmQuery
public void addChangeListener(RealmChangeListener<Realm> listener)
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.
listener
- the change listener.IllegalArgumentException
- if the change listener is null
.IllegalStateException
- if you try to register a listener from a non-Looper or IntentService
thread.RealmChangeListener
,
removeChangeListener(RealmChangeListener)
,
removeAllChangeListeners()
public void removeChangeListener(RealmChangeListener<Realm> 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 executeTransaction(Realm.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
- the Realm.Transaction
to execute.IllegalArgumentException
- if the transaction
is null
.RealmMigrationNeededException
- if the latest version contains incompatible schema changes.public RealmAsyncTask executeTransactionAsync(Realm.Transaction transaction)
executeTransaction(Transaction)
but runs asynchronously on a worker thread.transaction
- Realm.Transaction
to execute.RealmAsyncTask
representing a cancellable task.IllegalArgumentException
- if the transaction
is null
, or if the Realm is opened from
another thread.public RealmAsyncTask executeTransactionAsync(Realm.Transaction transaction, Realm.Transaction.OnSuccess onSuccess)
executeTransactionAsync(Transaction)
, but also accepts an OnSuccess callback.transaction
- Realm.Transaction
to execute.onSuccess
- callback invoked when the transaction succeeds.RealmAsyncTask
representing a cancellable task.IllegalArgumentException
- if the transaction
is null
, or if the realm is opened from
another thread.public RealmAsyncTask executeTransactionAsync(Realm.Transaction transaction, Realm.Transaction.OnError onError)
executeTransactionAsync(Transaction)
, but also accepts an OnError callback.transaction
- Realm.Transaction
to execute.onError
- callback invoked when the transaction fails.RealmAsyncTask
representing a cancellable task.IllegalArgumentException
- if the transaction
is null
, or if the realm is opened from
another thread.public RealmAsyncTask executeTransactionAsync(Realm.Transaction transaction, Realm.Transaction.OnSuccess onSuccess, Realm.Transaction.OnError onError)
executeTransactionAsync(Transaction)
, but also accepts an OnSuccess and OnError callbacks.transaction
- Realm.Transaction
to execute.onSuccess
- callback invoked when the transaction succeeds.onError
- callback invoked when the transaction fails.RealmAsyncTask
representing a cancellable task.IllegalArgumentException
- if the transaction
is null
, or if the realm is opened from
another thread.public void delete(Class<? extends RealmModel> clazz)
clazz
- the class which objects should be removed.IllegalStateException
- if the corresponding Realm is a query-based synchronized Realm, is
closed or called from an incorrect thread.public static void migrateRealm(RealmConfiguration configuration) throws FileNotFoundException
configuration
- RealmConfiguration
FileNotFoundException
- if the Realm file doesn't exist.public static void migrateRealm(RealmConfiguration configuration, RealmMigration migration) throws FileNotFoundException
configuration
- theRealmConfiguration
.migration
- the RealmMigration
to run on the Realm. This will override any migration set on the
configuration.FileNotFoundException
- if the Realm file doesn't exist.public static boolean deleteRealm(RealmConfiguration configuration)
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
IllegalStateException
. See issue https://github.com/realm/realm-java/issues/5416 .
configuration
- a RealmConfiguration
.false
if the Realm file could not be deleted. Temporary files deletion failure won't impact
the return value. All of the failing file deletions will be logged.IllegalStateException
- if there are Realm instances opened on other threads or other processes.public static boolean compactRealm(RealmConfiguration configuration)
The file must be closed before this method is called, otherwise false
will be returned.
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.
configuration
- a RealmConfiguration
pointing to a Realm file.true
if successful, false
if any file operation failed.public RealmAsyncTask unsubscribeAsync(String subscriptionName, Realm.UnsubscribeCallback callback)
RealmQuery.findAllAsync(String)
.
If after this, some objects are no longer part of any active subscription they will be removed
locally from the device (but not on the server).
The effect of unsubscribing is not immediate. The local Realm must coordinate with the Object
Server before this can happen. A successful callback just indicate that the request was
succesfully enqueued and any data will be removed as soon as possible. When the data is
actually removed locally, a standard change notification will be triggered and from the
perspective of the device it will look like the data was deleted.subscriptionName
- name of the subscription to removecallback
- callback reporting back if the intent to unsubscribe was enqueued successfully or failed.RealmAsyncTask
representing a cancellable task.IllegalArgumentException
- if no subscriptionName
or callback
was provided.IllegalStateException
- if called on a non-looper thread.UnsupportedOperationException
- if the Realm is not a query-based synchronized Realm.public RealmPermissions getPermissions()
RealmObject.addChangeListener(RealmChangeListener)
to be notified about
any future changes.public RealmResults<Role> getRoles()
Role
objects available in this Realm. Attach a change listener
using RealmObject.addChangeListener(RealmChangeListener)
to be notified about
any future changes.public ClassPrivileges getPrivileges(Class<? extends RealmModel> clazz)
clazz
- class to get privileges for.public ClassPermissions getPermissions(Class<? extends RealmModel> clazz)
RealmObject.addChangeListener(RealmChangeListener)
to be notified about
any future changes.clazz
- class to receive permissions for.null
if no permissions where found.RealmException
- if the class is not part of this Realms schema.public RealmResults<Subscription> getSubscriptions()
public RealmResults<Subscription> getSubscriptions(String pattern)
*
can be used to
indicate any number of unknown characters and ?
represents a single unknown character.pattern
- which subscriptions to find.IllegalArgumentException
- if an empty or null
pattern is provided.public Subscription getSubscription(String name)
name
- the name of the subscription to find.null
if no subscription matches the name.public static Object getDefaultModule()
null
if no default module exists.RealmException
- if unable to create an instance of the module.RealmConfiguration.Builder.modules(Object, Object...)
public static int getGlobalInstanceCount(RealmConfiguration configuration)
configuration
- the RealmConfiguration
for the Realm.public static int getLocalInstanceCount(RealmConfiguration configuration)
configuration
- the RealmConfiguration
for the 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 RealmPrivileges getPrivileges()
public ObjectPrivileges getPrivileges(RealmModel object)
object
- Realm object to get privileges for.IllegalArgumentException
- if the object is either null, unmanaged or not part of this Realm.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 void deleteAll()
If the Realm is a partially synchronized Realm, all subscriptions will be cleared as well.
IllegalStateException
- if the corresponding Realm is a partially synchronized Realm, is
closed or called from an incorrect thread.