Class Realm
- java.lang.Object
-
- io.realm.Realm
-
- All Implemented Interfaces:
Closeable,AutoCloseable
public class Realm extends Object
The Realm class is the storage and transactional manager of your object persistent store. It is in charge of creating instances of your RealmObjects. Objects within a Realm can be queried and read at any time. Creating, modifying, and deleting objects must be done while inside a transaction. SeeexecuteTransaction(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
Closeable.close()method when done with a Realm instance. Failing to do so can lead toOutOfMemoryErroras 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
Handlermechanism. This also means that Realm instances on threads without anLoopercannot receive updates unlessrefresh()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.
- See Also:
- ACID, Examples using Realm
-
-
Nested Class Summary
Nested Classes Modifier and Type Class Description static classRealm.CallbackThe Callback used when reporting back the result of loading a Realm asynchronously using eithergetInstanceAsync(RealmConfiguration, Realm.Callback)orDynamicRealm.getInstanceAsync(RealmConfiguration, DynamicRealm.Callback).static interfaceRealm.TransactionEncapsulates a Realm transaction.
-
Field Summary
Fields Modifier and Type Field Description static StringDEFAULT_REALM_NAMEstatic intENCRYPTION_KEY_LENGTHThe required length for encryption keys used to encrypt Realm data.static io.realm.BaseRealm.ThreadLocalRealmObjectContextobjectContextio.realm.internal.OsSharedRealmsharedRealmstatic io.realm.internal.async.RealmThreadPoolExecutorWRITE_EXECUTORThread 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 voidaddChangeListener(RealmChangeListener<Realm> listener)Adds a change listener to the Realm.Flowable<Realm>asFlowable()Returns an RxJava Flowable that monitors changes to this Realm.voidbeginTransaction()Starts a transaction which must be closed byBaseRealm.commitTransaction()or aborted byBaseRealm.cancelTransaction().voidcancelTransaction()Reverts all writes (created, updated, or deleted objects) made in the current write transaction and end the transaction.voidclose()Closes the Realm instance and all its resources.voidcommitTransaction()All changes sinceBaseRealm.beginTransaction()are persisted to disk and the Realm reverts back to being read-only.static booleancompactRealm(RealmConfiguration configuration)Compacts a Realm file.<E extends RealmModel>
EcopyFromRealm(E realmObject)Makes an unmanaged in-memory copy of an already persistedRealmObject.<E extends RealmModel>
EcopyFromRealm(E realmObject, int maxDepth)Makes an unmanaged in-memory copy of an already persistedRealmObject.<E extends RealmModel>
List<E>copyFromRealm(Iterable<E> realmObjects)Makes an unmanaged in-memory copy of already persisted RealmObjects.<E extends RealmModel>
List<E>copyFromRealm(Iterable<E> realmObjects, int maxDepth)Makes an unmanaged in-memory copy of already persisted RealmObjects.<E extends RealmModel>
EcopyToRealm(E object, ImportFlag... flags)Copies a RealmObject to the Realm instance and returns the copy.<E extends RealmModel>
List<E>copyToRealm(Iterable<E> objects, ImportFlag... flags)Copies a collection of RealmObjects to the Realm instance and returns their copy.<E extends RealmModel>
EcopyToRealmOrUpdate(E object, ImportFlag... flags)Updates an existing RealmObject that is identified by the samePrimaryKeyor creates a new copy if no existing object could be found.<E extends RealmModel>
List<E>copyToRealmOrUpdate(Iterable<E> objects, ImportFlag... flags)Updates a list of existing RealmObjects that is identified by theirPrimaryKeyor creates a new copy if no existing object could be found.<E extends RealmModel>
voidcreateAllFromJson(Class<E> clazz, InputStream inputStream)Creates a Realm object for each object in a JSON array.<E extends RealmModel>
voidcreateAllFromJson(Class<E> clazz, String json)Creates a Realm object for each object in a JSON array.<E extends RealmModel>
voidcreateAllFromJson(Class<E> clazz, JSONArray json)Creates a Realm object for each object in a JSON array.<E extends RealmModel>
EcreateEmbeddedObject(Class<E> clazz, RealmModel parentObject, String parentProperty)Instantiates and adds a new embedded object to the Realm.<E extends RealmModel>
EcreateObject(Class<E> clazz)Instantiates and adds a new object to the Realm.<E extends RealmModel>
EcreateObject(Class<E> clazz, Object primaryKeyValue)Instantiates and adds a new object to the Realm with the primary key value already set.<E extends RealmModel>
EcreateObjectFromJson(Class<E> clazz, InputStream inputStream)Creates a Realm object pre-filled with data from a JSON object.<E extends RealmModel>
EcreateObjectFromJson(Class<E> clazz, String json)Creates a Realm object pre-filled with data from a JSON object.<E extends RealmModel>
EcreateObjectFromJson(Class<E> clazz, JSONObject json)Creates a Realm object pre-filled with data from a JSON object.<E extends RealmModel>
voidcreateOrUpdateAllFromJson(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>
voidcreateOrUpdateAllFromJson(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>
voidcreateOrUpdateAllFromJson(Class<E> clazz, JSONArray json)Tries to update a list of existing objects identified by their primary key with new JSON data.<E extends RealmModel>
EcreateOrUpdateObjectFromJson(Class<E> clazz, InputStream in)Tries to update an existing object defined by its primary key with new JSON data.<E extends RealmModel>
EcreateOrUpdateObjectFromJson(Class<E> clazz, String json)Tries to update an existing object defined by its primary key with new JSON data.<E extends RealmModel>
EcreateOrUpdateObjectFromJson(Class<E> clazz, JSONObject json)Tries to update an existing object defined by its primary key with new JSON data.voiddelete(Class<? extends RealmModel> clazz)Deletes all objects of the specified class from the Realm.voiddeleteAll()Deletes all objects from this Realm.static booleandeleteRealm(RealmConfiguration configuration)Deletes the Realm file along with the related temporary files specified by the givenRealmConfigurationfrom the filesystem.voidexecuteTransaction(Realm.Transaction transaction)Executes a given transaction on the Realm.RealmAsyncTaskexecuteTransactionAsync(Realm.Transaction transaction)Similar toexecuteTransaction(Transaction)but runs asynchronously on a worker thread.RealmAsyncTaskexecuteTransactionAsync(Realm.Transaction transaction, Realm.Transaction.OnError onError)Similar toexecuteTransactionAsync(Transaction), but also accepts an OnError callback.RealmAsyncTaskexecuteTransactionAsync(Realm.Transaction transaction, Realm.Transaction.OnSuccess onSuccess)Similar toexecuteTransactionAsync(Transaction), but also accepts an OnSuccess callback.RealmAsyncTaskexecuteTransactionAsync(Realm.Transaction transaction, Realm.Transaction.OnSuccess onSuccess, Realm.Transaction.OnError onError)Similar toexecuteTransactionAsync(Transaction), but also accepts an OnSuccess and OnError callbacks.Realmfreeze()Returns a frozen snapshot of the current Realm.static ContextgetApplicationContext()Get the application context used when initializing Realm withinit(Context)orinit(Context, String).RealmConfigurationgetConfiguration()Returns theRealmConfigurationfor this Realm.static RealmConfigurationgetDefaultConfiguration()Returns the default configuration forgetDefaultInstance().static RealmgetDefaultInstance()Realm static constructor that returns the Realm instance defined by theRealmConfigurationset bysetDefaultConfiguration(RealmConfiguration)static ObjectgetDefaultModule()Returns the default Realm module.static intgetGlobalInstanceCount(RealmConfiguration configuration)Returns the current number of open Realm instances across all threads in current process that are using this configuration.static RealmgetInstance(RealmConfiguration configuration)Realm static constructor that returns the Realm instance defined by providedRealmConfigurationstatic RealmAsyncTaskgetInstanceAsync(RealmConfiguration configuration, Realm.Callback callback)The creation of the first Realm instance perRealmConfigurationin 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 intgetLocalInstanceCount(RealmConfiguration configuration)Returns the current number of open Realm instances on the thread calling this method.longgetNumberOfActiveVersions()Returns the current number of active versions currently being held by this Realm.StringgetPath()Returns the canonical path to where this Realm is persisted on disk.RealmSchemagetSchema()Returns the schema for this Realm.SubscriptionSetgetSubscriptions()Returns the subscription set associated with this Realm.longgetVersion()Returns the schema version for this Realm.static voidinit(Context context)Initializes the Realm library and creates a default configuration that is ready to use.static voidinit(Context context, String userAgent)Initializes the Realm library and creates a default configuration that is ready to use.voidinsert(RealmModel object)Inserts an unmanaged RealmObject.voidinsert(Collection<? extends RealmModel> objects)Inserts a list of an unmanaged RealmObjects.voidinsertOrUpdate(RealmModel object)Inserts or updates an unmanaged RealmObject.voidinsertOrUpdate(Collection<? extends RealmModel> objects)Inserts or updates a list of unmanaged RealmObjects.booleanisAutoRefresh()Retrieves the auto-refresh status of the Realm instance.booleanisClosed()Checks if theRealminstance has already been closed.booleanisEmpty()Checks if thisRealmcontains any objects.booleanisFrozen()Returns whether or not this Realm is frozen.booleanisInTransaction()Checks if the Realm is currently in a transaction.static voidmigrateRealm(RealmConfiguration configuration)Manually triggers the migration associated with a given RealmConfiguration.static voidmigrateRealm(RealmConfiguration configuration, RealmMigration migration)Manually triggers a migration on a RealmMigration.voidrefresh()Refreshes the Realm instance and all the RealmResults and RealmObjects instances coming from it.voidremoveAllChangeListeners()Removes all user-defined change listeners.voidremoveChangeListener(RealmChangeListener<Realm> listener)Removes the specified change listener.static voidremoveDefaultConfiguration()Removes the current default configuration (if any).voidsetAutoRefresh(boolean autoRefresh)Sets the auto-refresh status of the Realm instance.static voidsetDefaultConfiguration(RealmConfiguration configuration)Sets theRealmConfigurationused when callinggetDefaultInstance().voidstopWaitForChange()Deprecated.this method will be removed in the next-major releasebooleanwaitForChange()Deprecated.this method will be removed on the next-major release.<E extends RealmModel>
RealmQuery<E>where(Class<E> clazz)Returns a typed RealmQuery, which can be used to query for specific objects of this typevoidwriteCopyTo(File destination)Writes a compacted copy of the Realm to the given destination File.voidwriteEncryptedCopyTo(File destination, byte[] key)Writes a compacted and encrypted copy of the Realm to the given destination File.
-
-
-
Field Detail
-
DEFAULT_REALM_NAME
public static final String DEFAULT_REALM_NAME
- See Also:
- Constant Field Values
-
ENCRYPTION_KEY_LENGTH
public static final int ENCRYPTION_KEY_LENGTH
The required length for encryption keys used to encrypt Realm data.- See Also:
- Constant Field Values
-
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
-
asFlowable
public Flowable<Realm> 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 -onCompletewill 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 callonCompleteorOnError. - See Also:
- RxJava and Realm
-
isEmpty
public boolean isEmpty()
Checks if thisRealmcontains any objects.- Returns:
trueif empty, @{code false} otherwise.
-
getSchema
public RealmSchema getSchema()
Returns the schema for this Realm. The schema is immutable. Any attempt to modify it will result in anUnsupportedOperationException.The schema can only be modified using
DynamicRealm.getSchema()or through an migration.- Returns:
- The
RealmSchemafor this Realm.
-
init
public static void init(Context context)
Initializes the Realm library and creates a default configuration that is ready to use. It is required to call this method before interacting with any other of the Realm API's.A good place is in an
Applicationsubclass:public class MyApplication extends Application { \@Override public void onCreate() { super.onCreate(); Realm.init(this); } }Remember to register it in the
AndroidManifest.xmlfile:<?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>- Parameters:
context- the Application Context.- Throws:
IllegalArgumentException- if anullcontext is provided.IllegalStateException- ifContext.getFilesDir()could not be found.- See Also:
getDefaultInstance()
-
init
public static void init(Context context, String userAgent)
Initializes the Realm library and creates a default configuration that is ready to use. It is required to call this method before interacting with any other of the Realm API's.A good place is in an
Applicationsubclass: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.xmlfile:<?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>- Parameters:
context- the Application Context.userAgent- optional user defined string that will be sent to the Realm Object Server as part of aUser-Agentheader when a session is established. This setting will not be used by non-synchronized Realms.- Throws:
IllegalArgumentException- if anullcontext or userAgent is provided.IllegalStateException- ifContext.getFilesDir()could not be found.- See Also:
getDefaultInstance()
-
getDefaultInstance
public static Realm getDefaultInstance()
Realm static constructor that returns the Realm instance defined by theRealmConfigurationset bysetDefaultConfiguration(RealmConfiguration)- Returns:
- an instance of the Realm class.
- Throws:
NullPointerException- if no default configuration has been defined.RealmMigrationNeededException- if no migration has been provided by the default configuration and theRealmFileException- if an error happened when accessing the underlying Realm file. was set and the thread opening the Realm was interrupted while the download was in progress.
-
getInstance
public static Realm getInstance(RealmConfiguration configuration)
Realm static constructor that returns the Realm instance defined by providedRealmConfiguration- Parameters:
configuration-RealmConfigurationused to open the Realm- Returns:
- an instance of the Realm class
- Throws:
RealmMigrationNeededException- 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 nullRealmConfigurationis provided.- See Also:
for details on how to configure a Realm.
-
getInstanceAsync
public static RealmAsyncTask getInstanceAsync(RealmConfiguration configuration, Realm.Callback callback)
The creation of the first Realm instance perRealmConfigurationin 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-RealmConfigurationused to open the Realm.callback- invoked to return the results.- Returns:
- a
RealmAsyncTaskrepresenting a cancellable task. - Throws:
IllegalArgumentException- if a nullRealmConfigurationor a nullRealm.Callbackis provided.IllegalStateException- if it is called from a non-Looper orIntentServicethread.- See Also:
for more details.
-
setDefaultConfiguration
public static void setDefaultConfiguration(RealmConfiguration configuration)
Sets theRealmConfigurationused when callinggetDefaultInstance().- Parameters:
configuration- theRealmConfigurationto use as the default configuration.- Throws:
IllegalArgumentException- if a nullRealmConfigurationis provided.- See Also:
for details on how to configure a Realm.
-
getDefaultConfiguration
@Nullable public static RealmConfiguration getDefaultConfiguration()
Returns the default configuration forgetDefaultInstance().- Returns:
- default configuration object or
nullif no default configuration is specified.
-
removeDefaultConfiguration
public static void removeDefaultConfiguration()
Removes the current default configuration (if any). Any further calls togetDefaultInstance()will fail until a new default configuration has been set usingsetDefaultConfiguration(RealmConfiguration).
-
createAllFromJson
public <E extends RealmModel> void createAllFromJson(Class<E> clazz, JSONArray json)
Creates a Realm object for each object in a JSON array. This must be done within a transaction.JSON properties with unknown properties will be ignored. If a
RealmObjectfield is not present in the JSON object theRealmObjectfield will be set to the default value for that type.This method currently does not support value list field.
- Parameters:
clazz- type of Realm objects to create.json- an array where each JSONObject must map to the specified class.- Throws:
RealmException- if mapping from JSON fails.IllegalArgumentException- if the JSON object doesn't have a primary key property but the correspondingRealmObjectSchemahas aPrimaryKeydefined.UnsupportedOperationException- if the object to insert contains aRealmDictionaryor aRealmSet.- See Also:
RealmSet,RealmDictionary,RealmMap
-
createOrUpdateAllFromJson
public <E extends RealmModel> void createOrUpdateAllFromJson(Class<E> clazz, JSONArray json)
Tries to update a list of existing objects identified by their primary key with new JSON data. If an existing object could not be found in the Realm, a new object will be created. This must happen within a transaction. If updating aRealmObjectand a field is not found in the JSON object, that field will not be updated. If a newRealmObjectis created and a field is not found in the JSON object, that field will be assigned the default value for the field type.This method currently does not support value list field.
- Parameters:
clazz- type ofRealmObjectto create or update. It must have a primary key defined.json- array with object data.- Throws:
IllegalArgumentException- if trying to update a class without aPrimaryKey.IllegalArgumentException- if the JSON object doesn't have a primary key property but the correspondingRealmObjectSchemahas aPrimaryKeydefined.RealmException- if unable to map JSON.UnsupportedOperationException- if the object to insert contains aRealmDictionaryor aRealmSet.- See Also:
createAllFromJson(Class, org.json.JSONArray),RealmSet,RealmDictionary,RealmMap
-
createAllFromJson
public <E extends RealmModel> void createAllFromJson(Class<E> clazz, String json)
Creates a Realm object for each object in a JSON array. This must be done within a transaction. JSON properties with unknown properties will be ignored. If aRealmObjectfield is not present in the JSON object theRealmObjectfield will be set to the default value for that type.This method currently does not support value list field.
- Parameters:
clazz- type of Realm objects to create.json- the JSON array as a String where each object can map to the specified class.- Throws:
RealmException- if mapping from JSON fails.IllegalArgumentException- if the JSON object doesn't have a primary key property but the correspondingRealmObjectSchemahas aPrimaryKeydefined.UnsupportedOperationException- if the object to insert contains aRealmDictionaryor aRealmSet.- See Also:
RealmSet,RealmDictionary,RealmMap
-
createOrUpdateAllFromJson
public <E extends RealmModel> void createOrUpdateAllFromJson(Class<E> clazz, String json)
Tries to update a list of existing objects identified by their primary key with new JSON data. If an existing object could not be found in the Realm, a new object will be created. This must happen within a transaction. If updating aRealmObjectand a field is not found in the JSON object, that field will not be updated. If a newRealmObjectis created and a field is not found in the JSON object, that field will be assigned the default value for the field type.This method currently does not support value list field.
- Parameters:
clazz- type ofRealmObjectto create or update. It must have a primary key defined.json- string with an array of JSON objects.- Throws:
IllegalArgumentException- if trying to update a class without aPrimaryKey.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 correspondingRealmObjectSchemahas aPrimaryKeydefined.UnsupportedOperationException- if the object to insert contains aRealmDictionaryor aRealmSet.- See Also:
createAllFromJson(Class, String),RealmSet,RealmDictionary,RealmMap
-
createAllFromJson
public <E extends RealmModel> void createAllFromJson(Class<E> clazz, InputStream inputStream) throws IOException
Creates a Realm object for each object in a JSON array. This must be done within a transaction. JSON properties with unknown properties will be ignored. If aRealmObjectfield is not present in the JSON object theRealmObjectfield 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.
- Parameters:
clazz- type of Realm objects created.inputStream- the JSON array as a InputStream. All objects in the array must be of the specified class.- Throws:
RealmException- if mapping from JSON fails.IllegalArgumentException- if the JSON object doesn't have a primary key property but the correspondingRealmObjectSchemahas aPrimaryKeydefined.IOException- if something was wrong with the input stream.UnsupportedOperationException- if the object to insert contains aRealmDictionaryor aRealmSet.- See Also:
RealmSet,RealmDictionary,RealmMap
-
createOrUpdateAllFromJson
public <E extends RealmModel> void createOrUpdateAllFromJson(Class<E> clazz, InputStream in)
Tries to update a list of existing objects identified by their primary key with new JSON data. If an existing object could not be found in the Realm, a new object will be created. This must happen within a transaction. If updating aRealmObjectand a field is not found in the JSON object, that field will not be updated. If a newRealmObjectis 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.
- Parameters:
clazz- type ofRealmObjectto create or update. It must have a primary key defined.in- the InputStream with a list of object data in JSON format.- Throws:
IllegalArgumentException- if trying to update a class without aPrimaryKey.IllegalArgumentException- if the JSON object doesn't have a primary key property but the correspondingRealmObjectSchemahas aPrimaryKeydefined.RealmException- if unable to read JSON.UnsupportedOperationException- if the object to insert contains aRealmDictionaryor aRealmSet.- See Also:
createOrUpdateAllFromJson(Class, java.io.InputStream),RealmSet,RealmDictionary,RealmMap
-
createObjectFromJson
@Nullable public <E extends RealmModel> E createObjectFromJson(Class<E> clazz, JSONObject json)
Creates a Realm object pre-filled with data from a JSON object. This must be done inside a transaction. JSON properties with unknown properties will be ignored. If aRealmObjectfield is not present in the JSON object theRealmObjectfield will be set to the default value for that type.This method currently does not support value list field.
- Parameters:
clazz- type of Realm object to create.json- the JSONObject with object data.- Returns:
- created object or
nullif no JSON data was provided. - Throws:
RealmException- if the mapping from JSON fails.IllegalArgumentException- if the JSON object doesn't have a primary key property but the correspondingRealmObjectSchemahas aPrimaryKeydefined.UnsupportedOperationException- if the object to insert contains aRealmDictionaryor aRealmSet.- See Also:
createOrUpdateObjectFromJson(Class, org.json.JSONObject),RealmSet,RealmDictionary,RealmMap
-
createOrUpdateObjectFromJson
public <E extends RealmModel> E createOrUpdateObjectFromJson(Class<E> clazz, JSONObject json)
Tries to update an existing object defined by its primary key with new JSON data. If no existing object could be found a new object will be saved in the Realm. This must happen within a transaction. If updating aRealmObjectand a field is not found in the JSON object, that field will not be updated. If a newRealmObjectis created and a field is not found in the JSON object, that field will be assigned the default value for the field type.This method currently does not support value list field.
- Parameters:
clazz- Type ofRealmObjectto create or update. It must have a primary key defined.json-JSONObjectwith object data.- Returns:
- created or updated
RealmObject. - Throws:
IllegalArgumentException- if trying to update a class without aPrimaryKey.IllegalArgumentException- if the JSON object doesn't have a primary key property but the correspondingRealmObjectSchemahas aPrimaryKeydefined.RealmException- if JSON data cannot be mapped.UnsupportedOperationException- if the object to insert contains aRealmDictionaryor aRealmSet.- See Also:
createObjectFromJson(Class, org.json.JSONObject),RealmSet,RealmDictionary,RealmMap
-
createObjectFromJson
@Nullable public <E extends RealmModel> E createObjectFromJson(Class<E> clazz, String json)
Creates a Realm object pre-filled with data from a JSON object. This must be done inside a transaction. JSON properties with unknown properties will be ignored. If aRealmObjectfield is not present in the JSON object theRealmObjectfield will be set to the default value for that type.This method currently does not support value list field.
- Parameters:
clazz- type of Realm object to create.json- the JSON string with object data.- Returns:
- created object or
nullif JSON string was empty or null. - Throws:
RealmException- if mapping to json failed.IllegalArgumentException- if the JSON object doesn't have a primary key property but the correspondingRealmObjectSchemahas aPrimaryKeydefined.UnsupportedOperationException- if the object to insert contains aRealmDictionaryor aRealmSet.- See Also:
RealmSet,RealmDictionary,RealmMap
-
createOrUpdateObjectFromJson
public <E extends RealmModel> E createOrUpdateObjectFromJson(Class<E> clazz, String json)
Tries to update an existing object defined by its primary key with new JSON data. If no existing object could be found a new object will be saved in the Realm. This must happen within a transaction. If updating aRealmObjectand a field is not found in the JSON object, that field will not be updated. If a newRealmObjectis created and a field is not found in the JSON object, that field will be assigned the default value for the field type.This method currently does not support value list field.
- Parameters:
clazz- type ofRealmObjectto create or update. It must have a primary key defined.json- string with object data in JSON format.- Returns:
- created or updated
RealmObject. - Throws:
IllegalArgumentException- if trying to update a class without aPrimaryKey.IllegalArgumentException- if the JSON object doesn't have a primary key property but the correspondingRealmObjectSchemahas aPrimaryKeydefined.RealmException- if JSON object cannot be mapped from the string parameter.UnsupportedOperationException- if the object to insert contains aRealmDictionaryor aRealmSet.- See Also:
createObjectFromJson(Class, String),RealmSet,RealmDictionary,RealmMap
-
createObjectFromJson
@Nullable public <E extends RealmModel> E createObjectFromJson(Class<E> clazz, InputStream inputStream) throws IOException
Creates a Realm object pre-filled with data from a JSON object. This must be done inside a transaction. JSON properties with unknown properties will be ignored. If aRealmObjectfield is not present in the JSON object theRealmObjectfield 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.
- Parameters:
clazz- type of Realm object to create.inputStream- the JSON object data as a InputStream.- Returns:
- created object or
nullif JSON string was empty or null. - Throws:
RealmException- if the mapping from JSON failed.IllegalArgumentException- if the JSON object doesn't have a primary key property but the correspondingRealmObjectSchemahas aPrimaryKeydefined.IOException- if something went wrong with the input stream.UnsupportedOperationException- if the object to insert contains aRealmDictionaryor aRealmSet.- See Also:
RealmSet,RealmDictionary,RealmMap
-
createOrUpdateObjectFromJson
public <E extends RealmModel> E createOrUpdateObjectFromJson(Class<E> clazz, InputStream in)
Tries to update an existing object defined by its primary key with new JSON data. If no existing object could be found a new object will be saved in the Realm. This must happen within a transaction. If updating aRealmObjectand a field is not found in the JSON object, that field will not be updated. If a newRealmObjectis 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.
- Parameters:
clazz- type ofRealmObjectto create or update. It must have a primary key defined.in- theInputStreamwith object data in JSON format.- Returns:
- created or updated
RealmObject. - Throws:
IllegalArgumentException- if trying to update a class without aPrimaryKey.IllegalArgumentException- if the JSON object doesn't have a primary key property but the correspondingRealmObjectSchemahas aPrimaryKeydefined.RealmException- if failure to read JSON.UnsupportedOperationException- if the object to insert contains aRealmDictionaryor aRealmSet.- See Also:
createObjectFromJson(Class, java.io.InputStream),RealmSet,RealmDictionary,RealmMap
-
createObject
public <E extends RealmModel> E createObject(Class<E> clazz)
Instantiates and adds a new object to the Realm.This method is only available for model classes with no @PrimaryKey annotation. If you like to create an object that has a primary key, use
createObject(Class, Object)orcopyToRealm(RealmModel, ImportFlag...)instead.- Parameters:
clazz- the Class of the object to create.- Returns:
- the new object.
- Throws:
RealmException- if the primary key is defined in the model class or an object cannot be created.- See Also:
createObject(Class, Object)
-
createObject
public <E extends RealmModel> E createObject(Class<E> clazz, @Nullable Object primaryKeyValue)
Instantiates and adds a new object to the Realm with the primary key value already set.If the value violates the primary key constraint, no object will be added and a
RealmExceptionwill be thrown. The default value for primary key provided by the model class will be ignored.- Parameters:
clazz- the Class of the object to create.primaryKeyValue- value for the primary key field.- Returns:
- the new object.
- Throws:
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 theprimaryKeyValuedoesn't have a value that can be converted to the expected value.
-
createEmbeddedObject
public <E extends RealmModel> E createEmbeddedObject(Class<E> clazz, RealmModel 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:
clazz- the Class of the object to create. It must be marked with\@RealmClass(embedded = true).parentObject- The parent object which should hold a reference to the embedded object.parentProperty- the property in the parent class which holds the reference. If the parent property is a list the embedded object will be added to the end of that list.- Returns:
- the newly created embedded object.
- Throws:
IllegalArgumentException- ifclazzis not an embedded class or if the property in the parent class cannot hold objects of the appropriate type.- See Also:
RealmClass.embedded()
-
copyToRealm
public <E extends RealmModel> E copyToRealm(E object, ImportFlag... flags)
Copies a RealmObject to the Realm instance and returns the copy. Any further changes to the original RealmObject will not be reflected in the Realm copy. This is a deep copy, so all referenced objects will be copied. Objects already in this Realm will be ignored.Please note, copying an object will copy all field values. Any unset field in this and child objects will be set to their default value if not provided.
- Parameters:
object- theRealmObjectto copy to the Realm.flags- any flag that modifies the behaviour of inserting the data into the Realm.- Returns:
- a managed RealmObject with its properties backed by the Realm.
- Throws:
IllegalArgumentException- if the object isnullor it belongs to a Realm instance in a different thread.
-
copyToRealmOrUpdate
public <E extends RealmModel> E copyToRealmOrUpdate(E object, ImportFlag... flags)
Updates an existing RealmObject that is identified by the samePrimaryKeyor creates a new copy if no existing object could be found. This is a deep copy or update i.e., all referenced objects will be either copied or updated.Please note, copying an object will copy all field values. Any unset field in the object and child objects will be set to their default value if not provided.
- Parameters:
object-RealmObjectto copy or update.flags- any flag that modifies the behaviour of inserting the data into the Realm.- Returns:
- the new or updated RealmObject with all its properties backed by the Realm.
- Throws:
IllegalArgumentException- if the object isnullor doesn't have a Primary key defined or it belongs to a Realm instance in a different thread.- See Also:
copyToRealm(RealmModel, ImportFlag...)
-
copyToRealm
public <E extends RealmModel> List<E> copyToRealm(Iterable<E> objects, ImportFlag... flags)
Copies a collection of RealmObjects to the Realm instance and returns their copy. Any further changes to the original RealmObjects will not be reflected in the Realm copies. This is a deep copy i.e., all referenced objects will be copied. Objects already in this Realm will be ignored.Please note, copying an object will copy all field values. Any unset field in the objects and child objects will be set to their default value if not provided.
- Parameters:
objects- the RealmObjects to copy to the Realm.flags- any flag that modifies the behaviour of inserting the data into the Realm.- Returns:
- a list of the the converted RealmObjects that all has their properties managed by the Realm.
- Throws:
RealmException- if any of the objects has already been added to Realm.IllegalArgumentException- if any of the elements in the input collection isnull.
-
insert
public void insert(Collection<? extends RealmModel> objects)
Inserts a list of an unmanaged RealmObjects. This is generally faster thancopyToRealm(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:
- We don't check if the provided objects are already managed or not, so inserting a managed object might duplicate it. Duplication will only happen if the object doesn't have a primary key. Objects with primary keys will never get duplicated.
- We don't create (nor return) a managed
RealmObjectfor each element - 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
If you want the managed
RealmObjectreturned, usecopyToRealm(Iterable, ImportFlag...), otherwise if you have a large number of object this method is generally faster.- Parameters:
objects- RealmObjects to insert.- Throws:
IllegalStateException- if the corresponding Realm is closed, called from an incorrect thread or not in a transaction.
-
insert
public void insert(RealmModel object)
Inserts an unmanaged RealmObject. This is generally faster thancopyToRealm(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:
- We don't check if the provided objects are already managed or not, so inserting a managed object might duplicate it. Duplication will only happen if the object doesn't have a primary key. Objects with primary keys will never get duplicated.
- We don't create (nor return) a managed
RealmObjectfor each element - 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
If you want the managed
RealmObjectreturned, usecopyToRealm(RealmModel, ImportFlag...), otherwise if you have a large number of object this method is generally faster.- Parameters:
object- RealmObjects to insert.- Throws:
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.
-
insertOrUpdate
public void insertOrUpdate(Collection<? extends RealmModel> objects)
Inserts or updates a list of unmanaged RealmObjects. This is generally faster thancopyToRealmOrUpdate(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:
- We don't check if the provided objects are already managed or not, so inserting a managed object might duplicate it. Duplication will only happen if the object doesn't have a primary key. Objects with primary keys will never get duplicated.
- We don't create (nor return) a managed
RealmObjectfor each element - 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
If you want the managed
RealmObjectreturned, usecopyToRealm(Iterable, ImportFlag...), otherwise if you have a large number of object this method is generally faster.- Parameters:
objects- RealmObjects to insert.- Throws:
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.
-
insertOrUpdate
public void insertOrUpdate(RealmModel object)
Inserts or updates an unmanaged RealmObject. This is generally faster thancopyToRealmOrUpdate(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:
- We don't check if the provided objects are already managed or not, so inserting a managed object might duplicate it. Duplication will only happen if the object doesn't have a primary key. Objects with primary keys will never get duplicated.
- We don't create (nor return) a managed
RealmObjectfor each element - 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
If you want the managed
RealmObjectreturned, usecopyToRealm(RealmModel, ImportFlag...), otherwise if you have a large number of object this method is generally faster.- Parameters:
object- RealmObjects to insert.- Throws:
IllegalStateException- if the corresponding Realm is closed, called from an incorrect thread or not in a transaction.
-
copyToRealmOrUpdate
public <E extends RealmModel> List<E> copyToRealmOrUpdate(Iterable<E> objects, ImportFlag... flags)
Updates a list of existing RealmObjects that is identified by theirPrimaryKeyor creates a new copy if no existing object could be found. This is a deep copy or update i.e., all referenced objects will be either copied or updated.Please note, copying an object will copy all field values. Any unset field in the objects and child objects will be set to their default value if not provided.
- Parameters:
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.- Returns:
- a list of all the new or updated RealmObjects.
- Throws:
IllegalArgumentException- if RealmObject isnullor doesn't have a Primary key defined.- See Also:
copyToRealm(Iterable, ImportFlag...)
-
copyFromRealm
public <E extends RealmModel> List<E> copyFromRealm(Iterable<E> realmObjects)
Makes an unmanaged in-memory copy of already persisted RealmObjects. This is a deep copy that will copy all referenced objects.The copied objects are all detached from Realm and they will no longer be automatically updated. This means that the copied objects might contain data that are no longer consistent with other managed Realm objects.
*WARNING*: Any changes to copied objects can be merged back into Realm using
copyToRealmOrUpdate(RealmModel, ImportFlag...), but all fields will be overridden, not just those that were changed. This includes references to other objects, and can potentially override changes made by other threads. This behaviour can be modified usingImportFlags.- Type Parameters:
E- type of object.- Parameters:
realmObjects- RealmObjects to copy.- Returns:
- an in-memory detached copy of managed RealmObjects.
- Throws:
IllegalArgumentException- if the RealmObject is no longer accessible or it is aDynamicRealmObject.- See Also:
copyToRealmOrUpdate(Iterable, ImportFlag...)
-
copyFromRealm
public <E extends RealmModel> List<E> copyFromRealm(Iterable<E> realmObjects, int maxDepth)
Makes an unmanaged in-memory copy of already persisted RealmObjects. This is a deep copy that will copy all referenced objects up to the defined depth.The copied objects are all detached from Realm and they will no longer be automatically updated. This means that the copied objects might contain data that are no longer consistent with other managed Realm objects.
*WARNING*: Any changes to copied objects can be merged back into Realm using
copyToRealmOrUpdate(Iterable, ImportFlag...), but all fields will be overridden, not just those that were changed. This includes references to other objects even though they might benulldue tomaxDepthbeing reached. This can also potentially override changes made by other threads. This behaviour can be modified usingImportFlags.- Type Parameters:
E- type of object.- Parameters:
realmObjects- RealmObjects to copy.maxDepth- limit of the deep copy. All references after this depth will benull. Starting depth is0.- Returns:
- an in-memory detached copy of the RealmObjects.
- Throws:
IllegalArgumentException- ifmaxDepth < 0, the RealmObject is no longer accessible or it is aDynamicRealmObject.- See Also:
copyToRealmOrUpdate(Iterable, ImportFlag...)
-
copyFromRealm
public <E extends RealmModel> E copyFromRealm(E realmObject)
Makes an unmanaged in-memory copy of an already persistedRealmObject. 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 usingImportFlags.- Type Parameters:
E- type of object.- Parameters:
realmObject-RealmObjectto copy.- Returns:
- an in-memory detached copy of the managed
RealmObject. - Throws:
IllegalArgumentException- if the RealmObject is no longer accessible or it is aDynamicRealmObject.- See Also:
copyToRealmOrUpdate(RealmModel, ImportFlag...)
-
copyFromRealm
public <E extends RealmModel> E copyFromRealm(E realmObject, int maxDepth)
Makes an unmanaged in-memory copy of an already persistedRealmObject. 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 benulldue tomaxDepthbeing reached. This can also potentially override changes made by other threads. This behaviour can be modified usingImportFlags.- Type Parameters:
E- type of object.- Parameters:
realmObject-RealmObjectto copy.maxDepth- limit of the deep copy. All references after this depth will benull. Starting depth is0.- Returns:
- an in-memory detached copy of the managed
RealmObject. - Throws:
IllegalArgumentException- ifmaxDepth < 0, the RealmObject is no longer accessible or it is aDynamicRealmObject.- See Also:
copyToRealmOrUpdate(RealmModel, ImportFlag...)
-
where
public <E extends RealmModel> RealmQuery<E> where(Class<E> clazz)
Returns a typed RealmQuery, which can be used to query for specific objects of this type- Parameters:
clazz- the class of the object which is to be queried for.- Returns:
- a typed RealmQuery, which can be used to query for specific objects of this type.
- See Also:
RealmQuery
-
addChangeListener
public void addChangeListener(RealmChangeListener<Realm> 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 per thread singletons and cached, so listeners should be removed manually even if calling
Closeable.close(). Otherwise there is a risk of memory leaks.- Parameters:
listener- the change listener.- Throws:
IllegalArgumentException- if the change listener isnull.IllegalStateException- if you try to register a listener from a non-Looper orIntentServicethread.- See Also:
RealmChangeListener,removeChangeListener(RealmChangeListener),removeAllChangeListeners()
-
removeChangeListener
public void removeChangeListener(RealmChangeListener<Realm> 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
-
executeTransaction
public void executeTransaction(Realm.Transaction transaction)
Executes a given transaction on the Realm.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- theRealm.Transactionto execute.- Throws:
IllegalArgumentException- if thetransactionisnull.RealmMigrationNeededException- if the latest version contains incompatible schema changes.RealmException- if called from the UI thread, unless an explicit opt-in has been declared inRealmConfiguration.Builder.allowWritesOnUiThread(boolean).
-
executeTransactionAsync
public RealmAsyncTask executeTransactionAsync(Realm.Transaction transaction)
Similar toexecuteTransaction(Transaction)but runs asynchronously on a worker thread.- Parameters:
transaction-Realm.Transactionto execute.- Returns:
- a
RealmAsyncTaskrepresenting a cancellable task. - Throws:
IllegalArgumentException- if thetransactionisnull, or if the Realm is opened from another thread.
-
executeTransactionAsync
public RealmAsyncTask executeTransactionAsync(Realm.Transaction transaction, Realm.Transaction.OnSuccess onSuccess)
Similar toexecuteTransactionAsync(Transaction), but also accepts an OnSuccess callback.- Parameters:
transaction-Realm.Transactionto execute.onSuccess- callback invoked when the transaction succeeds.- Returns:
- a
RealmAsyncTaskrepresenting a cancellable task. - Throws:
IllegalArgumentException- if thetransactionisnull, or if the realm is opened from another thread.
-
executeTransactionAsync
public RealmAsyncTask executeTransactionAsync(Realm.Transaction transaction, Realm.Transaction.OnError onError)
Similar toexecuteTransactionAsync(Transaction), but also accepts an OnError callback.- Parameters:
transaction-Realm.Transactionto execute.onError- callback invoked when the transaction fails.- Returns:
- a
RealmAsyncTaskrepresenting a cancellable task. - Throws:
IllegalArgumentException- if thetransactionisnull, or if the realm is opened from another thread.
-
executeTransactionAsync
public RealmAsyncTask executeTransactionAsync(Realm.Transaction transaction, @Nullable Realm.Transaction.OnSuccess onSuccess, @Nullable Realm.Transaction.OnError onError)
Similar toexecuteTransactionAsync(Transaction), but also accepts an OnSuccess and OnError callbacks.- Parameters:
transaction-Realm.Transactionto execute.onSuccess- callback invoked when the transaction succeeds.onError- callback invoked when the transaction fails.- Returns:
- a
RealmAsyncTaskrepresenting a cancellable task. - Throws:
IllegalArgumentException- if thetransactionisnull, or if the realm is opened from another thread.
-
delete
public void delete(Class<? extends RealmModel> clazz)
Deletes all objects of the specified class from the Realm.- Parameters:
clazz- the class which objects should be removed.- Throws:
IllegalStateException- if the Realm is closed or called from an incorrect thread.
-
migrateRealm
public static void migrateRealm(RealmConfiguration configuration) throws FileNotFoundException
Manually triggers the migration associated with a given RealmConfiguration. If Realm is already at the latest version, nothing will happen.- Parameters:
configuration-RealmConfiguration- Throws:
FileNotFoundException- if the Realm file doesn't exist.
-
migrateRealm
public static void migrateRealm(RealmConfiguration configuration, @Nullable RealmMigration migration) throws FileNotFoundException
Manually triggers a migration on a RealmMigration.- Parameters:
configuration- theRealmConfiguration.migration- theRealmMigrationto run on the Realm. This will override any migration set on the configuration.- Throws:
FileNotFoundException- if the Realm file doesn't exist.
-
deleteRealm
public static boolean deleteRealm(RealmConfiguration configuration)
Deletes the Realm file along with the related temporary files specified by the givenRealmConfigurationfrom 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 .- Parameters:
configuration- aRealmConfiguration.- Returns:
falseif 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.- Throws:
IllegalStateException- if there are Realm instances opened on other threads or other processes.
-
compactRealm
public static boolean compactRealm(RealmConfiguration configuration)
Compacts a Realm file. A Realm file usually contain free/unused space. This method removes this free space and the file size is thereby reduced. Objects within the Realm files are untouched.The file must be closed before this method is called, otherwise
falsewill 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.- Parameters:
configuration- aRealmConfigurationpointing to a Realm file.- Returns:
trueif successful,falseif any file operation failed.
-
freeze
public Realm 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.
-
getDefaultModule
@Nullable public static Object getDefaultModule()
Returns the default Realm module. This module contains all Realm classes in the current project, but not those from library or project dependencies. Realm classes in these should be exposed using their own module.- Returns:
- the default Realm module or
nullif no default module exists. - Throws:
RealmException- if unable to create an instance of the module.- See Also:
RealmConfiguration.Builder.modules(Object, Object...)
-
getGlobalInstanceCount
public static int getGlobalInstanceCount(RealmConfiguration configuration)
Returns the current number of open Realm instances across all threads in current process that are using this configuration. This includes both dynamic and normal Realms.- Parameters:
configuration- theRealmConfigurationfor the Realm.- Returns:
- number of open Realm instances across all threads.
-
getLocalInstanceCount
public static int getLocalInstanceCount(RealmConfiguration configuration)
Returns the current number of open Realm instances on the thread calling this method. This include both dynamic and normal Realms.- Parameters:
configuration- theRealmConfigurationfor the Realm.- Returns:
- number of open Realm instances on the caller thread.
-
getApplicationContext
@Nullable public static Context getApplicationContext()
Get the application context used when initializing Realm withinit(Context)orinit(Context, String).- Returns:
- the application context used when initializing Realm with
init(Context)orinit(Context, String), or null if Realm has not been initialized yet.
-
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 an
Looperenabled thread.- Parameters:
autoRefresh-truewill turn auto-refresh on,falsewill 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
RealmExceptionifRealmConfiguration.Builder.allowQueriesOnUiThread(boolean)was used withtrueto obtain a Realm instance. In most cases it is better to useRealmChangeListeners 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:
trueif inside a transaction,falseotherwise.
-
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:
trueif the Realm was updated to the latest version,falseif it was cancelled by calling stopWaitForChange.- Throws:
IllegalStateException- if calling this from within a transaction or from a Looper thread.RealmMigrationNeededException- on typedRealmif 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()returnfalseimmediately. 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 theRealminstance 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 typedRealmif 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 andRealmResultsto 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:
trueif the Realm is frozen,falseif 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 theRealmConfigurationfor this Realm.- Returns:
- the
RealmConfigurationfor 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:
closein interfaceAutoCloseable- Specified by:
closein interfaceCloseable- Throws:
IllegalStateException- if attempting to close from another thread.
-
isClosed
public boolean isClosed()
Checks if theRealminstance has already been closed.- Returns:
trueif closed,falseotherwise.- 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.
-
-