io.realm
La clase Realm gestiona el almacenamiento y las transacciones de su almacén persistente de objetos. Se encarga de crear instancias de sus objetos Realm. Los objetos dentro de un Realm se pueden consultar y leer en cualquier momento. La creación, modificación y eliminación de objetos debe realizarse dentro de una transacción. Véase executeTransaction(Transaction)
The transactions ensure that multiple instances (on multiple threads) can access the same objects in a consistent state with full ACID guarantees.
It is important to remember to call the close() method when done with a Realm instance. Failing to do so can lead to java.lang.OutOfMemoryError as the native resources cannot be freed.
No se pueden usar instancias Realm en hilos diferentes. Esto quiere decir que debes abrir una instancia en cada hilo donde quieras usar Realm. Las instancias Realm se almacenan automáticamente en caché por hilo utilizando conteo de referencias, así que mientras el conteo de referencias no llegue a cero, llamar a getInstance(RealmConfiguration) sólo devolverá el Realm almacenado en caché y debe considerarse una operación ligera.
Para el hilo de la interfaz de usuario, esto significa que abrir y cerrar Realms debe ocurrir en onCreate/onDestroy o en onStart/onStop.
Realm instances coordinate their state across threads using the android.os.Handler mechanism. This also means that Realm instances on threads without an android.os.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 { 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; protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.layout_main); realm = Realm.getDefaultInstance(); } protected void onDestroy() { super.onDestroy(); realm.close(); } }
Realm supports String and byte fields containing up to 16 MB.
Nested Class Summary
Modificador y Tipo | Clase y descripción |
|---|---|
| |
|
Field Summary
Modificador y Tipo | Campo y Descripción |
|---|---|
public static final String | |
public static final int | La longitud requerida para las llaves de cifrado utilizadas para cifrar datos de Realm. |
Resumen del método
Modificador y Tipo | Método y descripción |
|---|---|
public void | Agrega un detector de cambios al Reino. |
public <any> | asFlowable () Returns an RxJava Flowable that monitors changes to this Realm. |
public static boolean | Compacts a Realm file. |
public E | Realiza una copia no gestionada en memoria de un RealmObject anteriormente persistido. |
public E | Realiza una copia no gestionada en memoria de un RealmObject anteriormente persistido. |
pública Lista | Crea una copia no administrada en memoria de RealmObjects ya persistentes. |
pública Lista | Crea una copia no administrada en memoria de RealmObjects ya persistentes. |
pública Lista | Copia una colección de RealmObjects en la instancia Realm y devuelve su copia. |
public E | Copies a RealmObject to the Realm instance and returns the copy. |
pública Lista | Updates a list of existing RealmObjects that is identified by their io.realm.annotations.PrimaryKey or creates a new copy if no existing object could be found. |
public E | Actualiza un RealmObject existente identificado por la misma io.realm.annotations.PrimaryKey o crea una nueva copia si no se pudo encontrar ningún objeto existente. |
public void | Creates a Realm object for each object in a JSON array. |
public E | Instantiates and adds a new embedded object to the Realm. |
public E | Instantiates and adds a new object to the Realm with the primary key value already set. |
public E | Instantiates and adds a new object to the Realm. |
public E | Creates a Realm object pre-filled with data from a JSON object. |
public void | Tries to update a list of existing objects identified by their primary key with new JSON data. |
public E | Tries to update an existing object defined by its primary key with new JSON data. |
public void | Deletes all objects of the specified class from the Realm. |
public static boolean | Elimina el archivo Realm junto con los archivos temporales relacionados especificados por la RealmConfiguration dada del sistema de archivos. |
public void | Executes a given transaction on the Realm. |
public RealmAsyncTask | Realm.Transaction transaction, Realm.Transaction.OnSuccess onSuccess, Realm.Transaction.OnError onError ) Similar to executeTransactionAsync(Transaction) , but also accepts an OnSuccess and OnError callbacks. |
public RealmAsyncTask | Similar a executeTransactionAsync(Transaction), pero también acepta una devolución de llamada OnError. |
public RealmAsyncTask | Similar a executeTransactionAsync(Transaction), pero también acepta una devolución de llamada OnSuccess. |
public RealmAsyncTask | Similar to executeTransaction(Transaction) but runs asynchronously on a worker thread. |
public Realm | freeze () Returns a frozen snapshot of the current Realm. |
public static Context | Get the application context used when initializing Realm with Realm.init(Context) or Realm.init(Context, String) . |
public static RealmConfiguration | Returns the default configuration for getDefaultInstance() . |
public static Realm | Realm static constructor that returns the Realm instance defined by the io.realm.RealmConfiguration set by setDefaultConfiguration(RealmConfiguration) |
public static objeto | Returns the default Realm module. |
public static int | Devuelve el número actual de instancias Realm abiertas en todos los hilos en el proceso actual que usan esta configuración. |
public static Realm | Realm static constructor that returns the Realm instance defined by provided io.realm.RealmConfiguration |
public static RealmAsyncTask | La creación de la primera instancia Realm por RealmConfiguration en un proceso puede tardar algún tiempo, ya que todo el código de inicialización debe ejecutarse en ese punto (configuración del Realm, validación de esquemas y creación de datos iniciales). |
public static int | Returns the current number of open Realm instances on the thread calling this method. |
public RealmSchema | getSchema () Devuelve el esquema para este reino. |
public static synchronized void | |
public static synchronized void | Inicializa la librería de Realm y crea una configuración por defecto que está lista para usar. |
public void | Inserts an unmanaged RealmObject. |
public void | Inserts a list of an unmanaged RealmObjects. |
public void | Inserta o actualiza un RealmObject no administrado. |
public void | Inserts or updates a list of unmanaged RealmObjects. |
public booleano | isEmpty () Comprueba si este io.realm.Realm contiene algún objeto. |
public static void | Activa manualmente una migración en un RealmMigration. |
public static void | Activa manualmente la migración asociada a una RealmConfiguration específica. |
public void | Removes all user-defined change listeners. |
public void | Removes the specified change listener. |
public static void | Removes the current default configuration (if any). |
public static void | Establece la io.realm.RealmConfiguration que se utiliza al llamar a getDefaultInstance() . |
Devuelve un RealmQuery tipado, que puede usarse para buscar objetos específicos de este tipo |
Inherited Methods
Methods inherited from class java.lang.Object :
getClass,hashCode,equals,clone,toString,notify,notifyAll,wait,wait,wait,finalizeMethods inherited from class io.realm.BaseRealm:
setAutoRefresh,isAutoRefresh,refresh,isInTransaction,addListener,removeListener,asFlowable,removeAllListeners,writeCopyTo,writeEncryptedCopyTo,waitForChange,stopWaitForChange,beginTransaction,commitTransaction,cancelTransaction,freeze,isFrozen,getNumberOfActiveVersions,checkIfValid,checkAllowQueriesOnUiThread,checkAllowWritesOnUiThread,checkIfInTransaction,checkIfValidAndInTransaction,getPath,getConfiguration,getVersion,close,isClosed,isEmpty,getSchema,getSubscriptions,deleteAll,migrateRealm,finalize
Detalle del Campo
DEFAULT_REALM_NAME
ENCRYPTION_KEY_LENGTH
La longitud requerida para las llaves de cifrado utilizadas para cifrar datos de Realm.
Detalle del método
addChangeListener
Adds a change listener to the Realm.The listeners will be executed when changes are committed by this or another thread. Las instancias Realm son "singletons" de hilo único y en caché, por lo que los escuchas deben eliminarse manualmente incluso si se invoca close(). De lo contrario, se corre el riesgo de fugas de memoria. Parámetros
Throws
|
asFlowable
public <any> 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 - Los elementos emitidos por Realm Flowables están congelados (consulta freeze()). Esto significa que son inmutables y pueden ser leídos en cualquier subproceso. 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: Si desea que Devuelve Observable de RxJava que solo llama a Anulaciones
|
compactRealm
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 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. Parámetros
Devuelve
|
copyFromRealm
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 Type Parameters
Parámetros
Devuelve an in-memory detached copy of the managed RealmObject . Throws
|
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 ImportFlag s. Type Parameters
Parámetros
Devuelve an in-memory detached copy of the managed RealmObject . Throws
|
Realiza una copia en memoria no administrada de objetos Realm ya persistentes. Esta copia profunda copia todos los objetos referenciados hasta la profundidad definida. Los objetos copiados se desvinculan de Realm y ya no se actualizan automáticamente. Esto significa que podrían contener datos que ya no son coherentes con otros objetos Realm administrados. *ADVERTENCIA*: Cualquier cambio realizado en objetos copiados puede fusionarse con Realm mediante copyToRealmOrUpdate(Iterable, ImportFlag...) , pero se sobrescribirán todos los campos, no solo aquellos que hayan sido modificados. Esto incluye referencias a otros objetos incluso si podrían ser Type Parameters
Parámetros
Devuelve an in-memory detached copy of the RealmObjects. Throws
|
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 ImportFlag s. Type Parameters
Parámetros
Devuelve an in-memory detached copy of managed RealmObjects. Throws
|
copyToRealm
Copia una colección de RealmObjects a la instancia de Realm y devuelve su copia. Cualquier cambio posterior a los RealmObjects originales no se reflejará en las copias de Realm. Se trata de una copia profunda, es decir, se copian todos los objetos referenciados. Los objetos que ya estén en este Realm se ignorarán. Tenga en cuenta que al copiar un objeto se copian todos los valores de los campos. Cualquier campo sin definir en los objetos y objetos secundarios se establecerá en su valor predeterminado si no se proporciona. Parámetros
Devuelve a list of the the converted RealmObjects that all has their properties managed by the Realm. Throws
|
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. Parámetros
Devuelve un RealmObject gestionado, con sus propiedades respaldadas por el Realm. Throws
|
copyToRealmOrUpdate
Updates a list of existing RealmObjects that is identified by their io.realm.annotations.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. Por favor, tenga en cuenta que al copiar un objeto se copiarán todos los valores de campo. Cualquier campo no configurado en los objetos y objetos hijos se establecerá en su valor por defecto si no se proporciona. Parámetros
Devuelve a list of all the new or updated RealmObjects. Throws
|
Updates an existing RealmObject that is identified by the same io.realm.annotations.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. Tenga en cuenta que copiar un objeto copiará todos los valores de los campos. Cualquier campo no establecido en el objeto y los objetos secundarios se establecerán en su valor por defecto si no se proporciona. Parámetros
Devuelve el RealmObject nuevo o actualizado con todas sus propiedades respaldadas por el Realm. Throws
|
createAllFromJson
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 method currently does not support value list field. Parámetros
Throws
|
crearObjetoIncrustado
public E createEmbeddedObject <E >( ) |
|---|
Instantiates and adds a new embedded object to the Realm.This method should only be used to create objects of types marked as embedded. Parámetros
Devuelve the newly created embedded object. Throws
|
createObject
Instancia y agrega un nuevo objeto al Realm con el valor de llave primaria ya configurado. Si el valor infringe la restricción de llave primaria, no se agregará ningún objeto y se lanzará una RealmException. El valor por defecto para la llave primaria proporcionado por la clase de modelo será ignorado. Parámetros
Devuelve the new object. Throws
|
Instancia y agrega un nuevo objeto al Realm. Este método solo está disponible para clases de modelo sin la anotación @PrimaryKey. Si deseas crear un objeto que tenga una llave primaria, utiliza createObject(Class, Object) o, en cambio, copyToRealm(RealmModel, ImportFlag...). Parámetros
Devuelve the new object. Throws
|
createObjectFromJson
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 a RealmObject field is not present in the JSON object the RealmObject field will be set to the default value for that type. This method currently does not support value list field. Parámetros
Devuelve created object or Throws
Tip
|
createOrUpdateAllFromJson
Intenta actualizar una lista de objetos existentes identificados por su clave primaria con nuevos datos JSON. Si un objeto existente no se encuentra en el Realm, se creará un nuevo objeto. Esto debe suceder dentro de una transacción. Si se actualiza un RealmObject y no se encuentra un campo en el objeto JSON, ese campo no se actualizará. Si se crea un nuevo RealmObject y no se encuentra un campo en el objeto JSON, ese campo se asignará al valor por defecto para el tipo de campo. This method currently does not support value list field. Parámetros
Throws
Tip
|
createOrUpdateObjectFromJson
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 a RealmObject and a field is not found in the JSON object, that field will not be updated. If a new RealmObject is created and a field is not found in the JSON object, that field will be assigned the default value for the field type. This method currently does not support value list field. Parámetros
Devuelve creó o actualizó io.realm.RealmObject. Throws
Tip
|
borrar
Deletes all objects of the specified class from the Realm. Parámetros
Throws
|
deleteRealm
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 Parámetros
Devuelve
Throws
|
ejecutarTransacción
Executes a given transaction on the Realm. beginTransaction() and commitTransaction() will be called automatically. If any exception is thrown during the transaction cancelTransaction() will be called instead of commitTransaction(). 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 using executeTransactionAsync(Transaction) instead. Parámetros
Throws
|
executeTransactionAsync
public RealmAsyncTask executeTransactionAsync ( Realm.Transaction transaction, Realm.Transaction.OnSuccess onSuccess, Realm.Transaction.OnError onError ) |
|---|
Similar to executeTransactionAsync(Transaction) , but also accepts an OnSuccess and OnError callbacks. Parámetros
Devuelve un RealmAsyncTask que representa una tarea cancelable. Throws
|
public RealmAsyncTask executeTransactionAsync ( Realm.Transaction transaction, Realm.Transaction.OnError onError ) |
|---|
Similar a executeTransactionAsync(Transaction), pero también acepta una devolución de llamada OnError. Parámetros
Devuelve un RealmAsyncTask que representa una tarea cancelable. Throws
|
public RealmAsyncTask executeTransactionAsync ( Realm.Transaction transaction, Realm.Transaction.OnSuccess onSuccess ) |
|---|
Similar a executeTransactionAsync(Transaction), pero también acepta una devolución de llamada OnSuccess. Parámetros
Devuelve un RealmAsyncTask que representa una tarea cancelable. Throws
|
Similar to executeTransaction(Transaction) but runs asynchronously on a worker thread. Parámetros
Devuelve un RealmAsyncTask que representa una tarea cancelable. Throws
|
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 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 . Nota: Mantener un gran número de Realms con diferentes versiones vivos puede tener un impacto negativo en el tamaño del archivo del Realm. Para evitar una situación así, es posible establecer RealmConfiguration.Builder.maxNumberOfActiveVersions(long) . Devuelve una copia congelada de este Reino. Anulaciones
|
getApplicationContext
public static Context getApplicationContext () |
|---|
Get the application context used when initializing Realm with Realm.init(Context) or Realm.init(Context, String) . Devuelve the application context used when initializing Realm with Realm.init(Context) or Realm.init(Context, String) , or null if Realm has not been initialized yet. |
getDefaultConfiguration
public static RealmConfiguration getDefaultConfiguration () |
|---|
Returns the default configuration for getDefaultInstance() . Devuelve default configuration object or |
getDefaultInstance
public static Realm getDefaultInstance () |
|---|
Realm static constructor that returns the Realm instance defined by the io.realm.RealmConfiguration set by setDefaultConfiguration(RealmConfiguration) Devuelve una instancia de la clase Realm. Throws
|
getDefaultModule
public static Object getDefaultModule () |
|---|
Devuelve el módulo Realm predeterminado. Este módulo contiene todas las clases Realm del proyecto actual, pero no las de las dependencias de la biblioteca o del proyecto. Las clases Realm que lo componen deben exponerse mediante su propio módulo. Devuelve el módulo Realm predeterminado o Throws
|
getGlobalInstanceCount
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. Parámetros
Devuelve número de instancias Realm abiertas en todos los hilos. |
getInstance
Realm static constructor that returns the Realm instance defined by provided io.realm.RealmConfiguration Parámetros
Devuelve an instance of the Realm class Throws
|
getInstanceAsync
public static RealmAsyncTask getInstanceAsync ( RealmConfiguration configuration, Realm.Callback callback ) |
|---|
The creation of the first Realm instance per RealmConfiguration in a process can take some time as all initialization code need to run at that point (setting up the Realm, validating schemas and creating initial data). 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. Parámetros
Devuelve un RealmAsyncTask que representa una tarea cancelable. Throws
|
getLocalInstanceCount
Returns the current number of open Realm instances on the thread calling this method. This include both dynamic and normal Realms. Parámetros
Devuelve number of open Realm instances on the caller thread. |
getSchema
public RealmSchema getSchema () |
|---|
Returns the schema for this Realm. The schema is immutable. Any attempt to modify it will result in an UnsupportedOperationException . The schema can only be modified using DynamicRealm.getSchema() or through an migration. Devuelve The RealmSchema for this Realm. Anulaciones
|
init
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 android.app.Application subclass: Recuerda registrarlo en el archivo Parámetros
Throws
|
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 android.app.Application subclass: Recuerda registrarlo en el archivo Parámetros
Throws
|
insert
Inserta un RealmObject no gestionado. Esto suele ser más rápido que copyToRealm(RealmModel, ImportFlag...) ya que no devuelve los elementos insertados y realiza asignaciones y comprobaciones mínimas. Una vez insertado, cualquier cambio realizado en el objeto original no se persistirá. Please note:
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. Parámetros
Throws
|
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:
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. Parámetros
Throws
|
insertOrUpdate
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:
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. Parámetros
Throws
|
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:
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. Parámetros
Throws
|
isEmpty
public boolean isEmpty () |
|---|
Comprueba si este io.realm.Realm contiene algún objeto. Devuelve
Anulaciones
|
migrateRealm
Activa manualmente una migración en un RealmMigration. Parámetros
Throws
|
Manually triggers the migration associated with a given RealmConfiguration. If Realm is already at the latest version, nothing will happen. Parámetros
Throws
|
removeAllChangeListeners
public void removeAllChangeListeners () |
|---|
Removes all user-defined change listeners. Throws
|
removeChangeListener
Removes the specified change listener. Parámetros
Throws
|
removeDefaultConfiguration
public static void removeDefaultConfiguration () |
|---|
Remueve la configuración por defecto actual (si hay alguna). Cualquier llamada posterior a getDefaultInstance() fallará hasta que se haya establecido una nueva configuración predeterminada usando setDefaultConfiguration(RealmConfiguration) . |
setDefaultConfiguration
Establece la io.realm.RealmConfiguration que se utiliza al llamar a getDefaultInstance() . Parámetros
Throws
|
dónde
Devuelve un RealmQuery tipado, que puede usarse para buscar objetos específicos de este tipo Parámetros
Devuelve a typed RealmQuery, which can be used to query for specific objects of this type. |