Package io.realm

Class 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. See executeTransaction(Transaction)

    The transactions ensure that multiple instances (on multiple threads) can access the same objects in a consistent state with full ACID guarantees.

    It is important to remember to call the Closeable.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 refresh() 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
    • Field Detail

      • 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 - onComplete will never be called.

        Items emitted from Realm Flowables are frozen (See freeze(). This means that they are immutable and can be read on any thread.

        Realm Flowables always emit items from the thread holding the live Realm. This means that if you need to do further processing, it is recommend to observe the values on a computation scheduler:

        realm.asFlowable() .observeOn(Schedulers.computation()) .map(rxRealm -> doExpensiveWork(rxRealm)) .observeOn(AndroidSchedulers.mainThread()) .subscribe( ... );

        If you would like the asFlowable() to stop emitting items, you can instruct RxJava to only emit only the first item by using the first() operator:

         
         realm.asFlowable().first().subscribe( ... ); // You only get the results once
         
         
        Returns:
        RxJava Observable that only calls onNext. It will never call onComplete or OnError.
        See Also:
        RxJava and Realm
      • isEmpty

        public boolean isEmpty()
        Checks if this Realm contains any objects.
        Returns:
        true if empty, @{code false} otherwise.
      • 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 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>
         
         
        Parameters:
        context - the Application Context.
        Throws:
        IllegalArgumentException - if a null context is provided.
        IllegalStateException - if Context.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 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>
         
         
        Parameters:
        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.
        Throws:
        IllegalArgumentException - if a null context or userAgent is provided.
        IllegalStateException - if Context.getFilesDir() could not be found.
        See Also:
        getDefaultInstance()
      • getDefaultConfiguration

        @Nullable
        public static RealmConfiguration getDefaultConfiguration()
        Returns the default configuration for getDefaultInstance().
        Returns:
        default configuration object or null if no default configuration is specified.
      • 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 a 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.

        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 corresponding RealmObjectSchema has a PrimaryKey defined.
        IOException - if something was wrong with the input stream.
        UnsupportedOperationException - if the object to insert contains a RealmDictionary or a RealmSet.
        See Also:
        RealmSet, RealmDictionary, RealmMap
      • 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 RealmException will 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 the primaryKeyValue doesn'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 - if clazz is 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 - the RealmObject to 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 is null or 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 same PrimaryKey or creates a new copy if no existing object could be found. This is a deep copy or update i.e., all referenced objects will be either copied or updated.

        Please note, copying an object will copy all field values. Any unset field in the object and child objects will be set to their default value if not provided.

        Parameters:
        object - RealmObject to 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 is null or 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 RealmModelList<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 is null.
      • insert

        public void insert​(Collection<? extends RealmModel> objects)
        Inserts a list of an unmanaged RealmObjects. This is generally faster than copyToRealm(Iterable, ImportFlag...) since it doesn't return the inserted elements, and performs minimum allocations and checks. After being inserted any changes to the original objects will not be persisted.

        Please note:

        • 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 RealmObject for 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 RealmObject returned, use copyToRealm(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 than copyToRealm(RealmModel, ImportFlag...) since it doesn't return the inserted elements, and performs minimum allocations and checks. After being inserted any changes to the original object will not be persisted.

        Please note:

        • 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 RealmObject for 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 RealmObject returned, use copyToRealm(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 than copyToRealmOrUpdate(Iterable, ImportFlag...) since it doesn't return the inserted elements, and performs minimum allocations and checks. After being inserted any changes to the original objects will not be persisted.

        Please note:

        • 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 RealmObject for 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 RealmObject returned, use copyToRealm(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 than copyToRealmOrUpdate(RealmModel, ImportFlag...) since it doesn't return the inserted elements, and performs minimum allocations and checks. After being inserted any changes to the original object will not be persisted.

        Please note:

        • 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 RealmObject for 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 RealmObject returned, use copyToRealm(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 RealmModelList<E> 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. 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 is null or doesn't have a Primary key defined.
        See Also:
        copyToRealm(Iterable, ImportFlag...)
      • copyFromRealm

        public <E extends RealmModelList<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 using ImportFlags.

        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 a DynamicRealmObject.
        See Also:
        copyToRealmOrUpdate(Iterable, ImportFlag...)
      • copyFromRealm

        public <E extends RealmModelList<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 be null due to maxDepth being reached. This can also potentially override changes made by other threads. This behaviour can be modified using ImportFlags.

        Type Parameters:
        E - type of object.
        Parameters:
        realmObjects - RealmObjects to copy.
        maxDepth - limit of the deep copy. All references after this depth will be null. Starting depth is 0.
        Returns:
        an in-memory detached copy of the RealmObjects.
        Throws:
        IllegalArgumentException - if maxDepth < 0, the RealmObject is no longer accessible or it is a DynamicRealmObject.
        See Also:
        copyToRealmOrUpdate(Iterable, ImportFlag...)
      • copyFromRealm

        public <E extends RealmModel> E copyFromRealm​(E realmObject)
        Makes an unmanaged in-memory copy of an already persisted RealmObject. This is a deep copy that will copy all referenced objects.

        The copied object(s) are all detached from Realm and they will no longer be automatically updated. This means that the copied objects might contain data that are no longer consistent with other managed Realm objects.

        *WARNING*: Any changes to copied objects can be merged back into Realm using copyToRealmOrUpdate(RealmModel, ImportFlag...), but all fields will be overridden, not just those that were changed. This includes references to other objects, and can potentially override changes made by other threads. This behaviour can be modified using ImportFlags.

        Type Parameters:
        E - type of object.
        Parameters:
        realmObject - RealmObject to copy.
        Returns:
        an in-memory detached copy of the managed RealmObject.
        Throws:
        IllegalArgumentException - if the RealmObject is no longer accessible or it is a DynamicRealmObject.
        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 persisted RealmObject. This is a deep copy that will copy all referenced objects up to the defined depth.

        The copied object(s) are all detached from Realm and they will no longer be automatically updated. This means that the copied objects might contain data that are no longer consistent with other managed Realm objects.

        *WARNING*: Any changes to copied objects can be merged back into Realm using copyToRealmOrUpdate(RealmModel, ImportFlag...), but all fields will be overridden, not just those that were changed. This includes references to other objects even though they might be null due to maxDepth being reached. This can also potentially override changes made by other threads. This behaviour can be modified using ImportFlags.

        Type Parameters:
        E - type of object.
        Parameters:
        realmObject - RealmObject to copy.
        maxDepth - limit of the deep copy. All references after this depth will be null. Starting depth is 0.
        Returns:
        an in-memory detached copy of the managed RealmObject.
        Throws:
        IllegalArgumentException - if maxDepth < 0, the RealmObject is no longer accessible or it is a DynamicRealmObject.
        See Also:
        copyToRealmOrUpdate(RealmModel, ImportFlag...)
      • where

        public <E extends RealmModelRealmQuery<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
      • removeAllChangeListeners

        public void removeAllChangeListeners()
        Removes all user-defined change listeners.
        Throws:
        IllegalStateException - if you try to remove listeners from a non-Looper Thread.
        See Also:
        RealmChangeListener
      • delete

        public void delete​(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.
      • deleteRealm

        public static boolean deleteRealm​(RealmConfiguration configuration)
        Deletes the Realm file along with the related temporary files specified by the given RealmConfiguration from the filesystem. Temporary file with ".lock" extension won't be deleted.

        All Realm instances must be closed before calling this method.

        WARNING: For synchronized Realm, there is a chance that an internal Realm instance on the background thread is not closed even all the user controlled Realm instances are closed. This will result an IllegalStateException. See issue https://github.com/realm/realm-java/issues/5416 .

        Parameters:
        configuration - a RealmConfiguration.
        Returns:
        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.
        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 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.

        Parameters:
        configuration - a RealmConfiguration pointing to a Realm file.
        Returns:
        true if successful, false if 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 an IllegalStateException. A frozen Realm has its own lifecycle and can be closed by calling Closeable.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 null if 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 - the RealmConfiguration for 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 - the RealmConfiguration for the Realm.
        Returns:
        number of open Realm instances on the caller thread.
      • setAutoRefresh

        public void setAutoRefresh​(boolean autoRefresh)
        Sets the auto-refresh status of the Realm instance.

        Auto-refresh is a feature that enables automatic update of the current Realm instance and all its derived objects (RealmResults and RealmObject instances) when a commit is performed on a Realm acting on the same file in another thread. This feature is only available if the Realm instance lives on a Looper enabled thread.

        Parameters:
        autoRefresh - true will turn auto-refresh on, false will turn it off.
        Throws:
        IllegalStateException - if called from a non-Looper thread.
      • isAutoRefresh

        public boolean isAutoRefresh()
        Retrieves the auto-refresh status of the Realm instance.
        Returns:
        the auto-refresh status.
      • isInTransaction

        public boolean isInTransaction()
        Checks if the Realm is currently in a transaction.
        Returns:
        true if inside a transaction, false otherwise.
      • writeCopyTo

        public void writeCopyTo​(File destination)
        Writes a compacted copy of the Realm to the given destination File. The resulting file can be used as initial dataset to bootstrap a local or synced Realm in other devices.

        The destination file cannot already exist.

        Note that if this is called from within a transaction it writes the current data, and not the data as it was when the last transaction was committed.

        Parameters:
        destination - file to save the Realm to.
        Throws:
        IllegalArgumentException - if destination argument is null.
        RealmFileException - if an error happened when accessing the underlying Realm file or writing to the destination file.
        IllegalStateException - if called from the UI thread.
        IllegalStateException - if not all client changes are integrated in server.
      • writeEncryptedCopyTo

        public void writeEncryptedCopyTo​(File destination,
                                         byte[] key)
        Writes a compacted and encrypted copy of the Realm to the given destination File. The resulting file can be used as initial dataset to bootstrap a local or synced Realm in other devices.

        The destination file cannot already exist.

        Note that if this is called from within a transaction it writes the current data, and not the data as it was when the last transaction was committed.

        Parameters:
        destination - file to save the Realm to.
        key - a 64-byte encryption key.
        Throws:
        IllegalArgumentException - if destination argument is null.
        RealmFileException - if an error happened when accessing the underlying Realm file or writing to the destination file.
        IllegalStateException - if called from the UI thread.
        IllegalStateException - if not all client changes are integrated in server.
      • waitForChange

        @Deprecated
        public boolean waitForChange()
        Deprecated.
        this method will be removed on the next-major release.
        Blocks the current thread until new changes to the Realm are available or stopWaitForChange() is called from another thread. Once stopWaitForChange is called, all future calls to this method will return false immediately.
        Returns:
        true if the Realm was updated to the latest version, false if it was cancelled by calling stopWaitForChange.
        Throws:
        IllegalStateException - if calling this from within a transaction or from a Looper thread.
        RealmMigrationNeededException - on typed Realm if the latest version contains incompatible schema changes.
      • stopWaitForChange

        @Deprecated
        public void stopWaitForChange()
        Deprecated.
        this method will be removed in the next-major release
        Makes any current 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.

        Throws:
        IllegalStateException - if the Realm instance has already been closed.
      • beginTransaction

        public void beginTransaction()
        Starts a transaction which must be closed by 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.

        Throws:
        RealmMigrationNeededException - on typed Realm if the latest version contains incompatible schema changes.
      • commitTransaction

        public void commitTransaction()
        All changes since 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.
      • cancelTransaction

        public void cancelTransaction()
        Reverts all writes (created, updated, or deleted objects) made in the current write transaction and end the transaction.

        The Realm reverts back to read-only.

        Calling this when not in a transaction will throw an exception.

      • isFrozen

        public boolean isFrozen()
        Returns whether or not this Realm is frozen.
        Returns:
        true if the Realm is frozen, false if it is not.
        See Also:
        freeze()
      • getNumberOfActiveVersions

        public long getNumberOfActiveVersions()
        Returns the current number of active versions currently being held by this Realm.

        Having a large number of active versions have a negative impact on the size of the Realm file. See the FAQ for more information.

        Returns:
        number of active versions currently being held by the Realm.
        See Also:
        RealmConfiguration.Builder.maxNumberOfActiveVersions(long)
      • getPath

        public String getPath()
        Returns the canonical path to where this Realm is persisted on disk.
        Returns:
        the canonical path to the Realm file.
        See Also:
        File.getCanonicalPath()
      • getVersion

        public long getVersion()
        Returns the schema version for this Realm.
        Returns:
        the schema version for the Realm file backing this Realm.
      • close

        public void close()
        Closes the Realm instance and all its resources.

        It's important to always remember to close Realm instances when you're done with it in order not to leak memory, file descriptors or grow the size of Realm file out of measure.

        Specified by:
        close in interface AutoCloseable
        Specified by:
        close in interface Closeable
        Throws:
        IllegalStateException - if attempting to close from another thread.
      • isClosed

        public boolean isClosed()
        Checks if the Realm instance has already been closed.
        Returns:
        true if closed, false otherwise.
        Throws:
        IllegalStateException - if attempting to close from another thread.
      • getSubscriptions

        public SubscriptionSet getSubscriptions()
        Returns the subscription set associated with this Realm. The subscription set defines a set of queries that define which data is synchronized between this realm and the server.

        This method is only applicable to synchronized realms using flexible sync.

        Returns:
        the subscription set associated with this realm.
        Throws:
        IllegalStateException - if this realm is either a local realm or a partion-based synchronized realm.
      • deleteAll

        public void deleteAll()
        Deletes all objects from this Realm.
        Throws:
        IllegalStateException - if the Realm is closed or called from an incorrect thread.