Join us at MongoDB.local London on 7 May to unlock new possibilities for your data. Use WEB50 to save 50%.
Register now >
Docs Menu
Docs Home
/ /
io.realm

Class Realm

java.lang.Object
io.realm.BaseRealm
io.realm.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 {
@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.

Tip

  • ACID

  • Ejemplos usando Realm

Modificador y Tipo
Clase y descripción

public static interface

public abstract static

Modificador y Tipo
Campo y Descripción

public static final String

public static final int

ENCRYPTION_KEY_LENGTH

La longitud requerida para las llaves de cifrado utilizadas para cifrar datos de Realm.

Modificador y Tipo
Método y descripción

public void

Agrega un detector de cambios al Reino.

public <any>

Returns an RxJava Flowable that monitors changes to this Realm.

public static boolean

Compacts a Realm file.

public E

E realmObject,
int maxDepth
)

Realiza una copia no gestionada en memoria de un RealmObject anteriormente persistido.

public E

E realmObject
)

Realiza una copia no gestionada en memoria de un RealmObject anteriormente persistido.

pública Lista

java.lang.Iterable<E> realmObjects,
int maxDepth
)

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

E object,
)

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

JSONArray json
)

Creates a Realm object for each object in a JSON array.

public E

RealmModel parentObject,
String parentProperty
)

Instantiates and adds a new embedded object to the Realm.

public E

Object primaryKeyValue
)

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

JSONObject json
)

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.

Similar to executeTransactionAsync(Transaction) , but also accepts an OnSuccess and OnError callbacks.

Similar a executeTransactionAsync(Transaction), pero también acepta una devolución de llamada OnError.

Similar a executeTransactionAsync(Transaction), pero también acepta una devolución de llamada OnSuccess.

Similar to executeTransaction(Transaction) but runs asynchronously on a worker thread.

public Realm

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.

Devuelve el esquema para este reino.

public static synchronized void

Context context,
String userAgent
)

Inicializa la librería de Realm y crea una configuración por defecto que está lista para usar.

public static synchronized void

Context context
)

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

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

  • Methods inherited from class java.lang.Object : getClass , hashCode , equals , clone , toString , notify , notifyAll , wait , wait , wait , finalize

  • Methods 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

La longitud requerida para las llaves de cifrado utilizadas para cifrar datos de Realm.

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

  • listener - the change listener.

Throws

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

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:

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

Si desea que asFlowable() deje de emitir elementos, puede indicarle a RxJava que solo emita el primer elemento utilizando el operador first():

realm.asFlowable().first().subscribe( ... ); // You only get the results once

Devuelve

Observable de RxJava que solo llama a onNext . Nunca llamará a onComplete ni a OnError .

Anulaciones

asFlowable in class BaseRealm

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.

Parámetros

Devuelve

true si tiene éxito, false si alguna operación de archivo falló.

public E copyFromRealm <E >(
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 ImportFlag s.

Type Parameters

  • E - type of object.

Parámetros

  • realmObject - RealmObject to copy.

  • maxDepth Límite de la copia profunda. Todas las referencias posteriores a esta profundidad serán null . La profundidad inicial es 0 .

Devuelve

an in-memory detached copy of the managed RealmObject .

Throws

public E copyFromRealm <E >(
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 ImportFlag s.

Type Parameters

  • E - type of object.

Parámetros

Devuelve

an in-memory detached copy of the managed RealmObject .

Throws

public List copyFromRealm <E >(
java.lang.Iterable<E> realmObjects,
int maxDepth
)

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 null debido a que se alcanzó maxDepth. Esto también podría sobrescribir cambios realizados por otros hilos. Este comportamiento se puede modificar utilizando ImportFlag s.

Type Parameters

  • E - type of object.

Parámetros

  • realmObjects - RealmObjects to copy.

  • maxDepth Límite de la copia profunda. Todas las referencias posteriores a esta profundidad serán null . La profundidad inicial es 0 .

Devuelve

an in-memory detached copy of the RealmObjects.

Throws

public List copyFromRealm <E >(
)

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

  • E - type of object.

Parámetros

  • realmObjects - RealmObjects to copy.

Devuelve

an in-memory detached copy of managed RealmObjects.

Throws

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

  • objects - los RealmObjects a copiar en el Realm.

  • flags - cualquier bandera que modifique el comportamiento de inserción de los datos en Realm.

Devuelve

a list of the the converted RealmObjects that all has their properties managed by the Realm.

Throws

public E copyToRealm <E >(
E object,
)

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

  • object - the io.realm.RealmObject to copy to the Realm.

  • flags - cualquier bandera que modifique el comportamiento de inserción de los datos en Realm.

Devuelve

un RealmObject gestionado, con sus propiedades respaldadas por el Realm.

Throws

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

  • objects - a list of objects to update or copy into Realm.

  • flags - cualquier bandera que modifique el comportamiento de inserción de los datos en Realm.

Devuelve

a list of all the new or updated RealmObjects.

Throws

public E copyToRealmOrUpdate <E >(
E object,
)

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

  • object - io.realm.RealmObject to copy or update.

  • flags - cualquier bandera que modifique el comportamiento de inserción de los datos en Realm.

Devuelve

el RealmObject nuevo o actualizado con todas sus propiedades respaldadas por el Realm.

Throws

public void createAllFromJson <E >(
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 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

  • clazz - tipo de objetos Realm para crear.

  • json - an array where each JSONObject must map to the specified class.

Throws

public E createEmbeddedObject <E >(
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.

Parámetros

  • clazz - the Class of the object to create. It must be marked with @RealmClass(embedded = true) .

  • parentObject - El objeto padre que debe contener una referencia al objeto incrustado.

  • parentProperty - la propiedad en la clase principal que contiene la referencia. Si la propiedad principal es una lista, el objeto incrustado se añadirá al final de esa lista.

Devuelve

the newly created embedded object.

Throws

  • IllegalArgumentException - si clazz no es una clase embebida o si la propiedad de la clase padre no puede contener objetos del tipo adecuado.

public E createObject <E >(
Object primaryKeyValue
)

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

  • clazz - la clase del objeto a crear.

  • primaryKeyValue - valor para el campo de clave principal.

Devuelve

the new object.

Throws

public E createObject <E >(
)

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

  • clazz - la clase del objeto a crear.

Devuelve

the new object.

Throws

  • RealmException - if the primary key is defined in the model class or an object cannot be created.

public E createObjectFromJson <E >(
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 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

  • clazz - type of Realm object to create.

  • json - the JSONObject with object data.

Devuelve

created object or null if no JSON data was provided.

Throws

Tip

public void createOrUpdateAllFromJson <E >(
JSONArray json
)

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

  • clazz - type of io.realm.RealmObject to create or update. It must have a primary key defined.

  • json - array with object data.

Throws

Tip

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 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

  • clazz - Type of io.realm.RealmObject to create or update. It must have a primary key defined.

  • json - org.json.JSONObject with object data.

Devuelve

creó o actualizó io.realm.RealmObject.

Throws

Tip

Deletes all objects of the specified class from the Realm.

Parámetros

  • clazz - la clase para la cual se deben eliminar objetos.

Throws

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 .

Parámetros

Devuelve

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

public void executeTransaction (
Realm.Transaction transaction
)

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

Similar to executeTransactionAsync(Transaction) , but also accepts an OnSuccess and OnError callbacks.

Parámetros

  • transaction - io.realm.Realm.Transaction to execute.

  • onSuccess - callback invoked when the transaction succeeds.

  • onError - función de retorno invocada cuando la transacción falla.

Devuelve

un RealmAsyncTask que representa una tarea cancelable.

Throws

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

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

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 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

freeze in class BaseRealm

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.

Returns the default configuration for getDefaultInstance() .

Devuelve

default configuration object or null if no default configuration is specified.

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

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 null si no existe ningún módulo predeterminado.

Throws

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.

Parámetros

Devuelve

número de instancias Realm abiertas en todos los hilos.

public static Realm getInstance (
RealmConfiguration configuration
)

Realm static constructor that returns the Realm instance defined by provided io.realm.RealmConfiguration

Parámetros

Devuelve

an instance of the Realm class

Throws

RealmConfiguration configuration,
)

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

  • configuration - RealmConfiguration used to open the Realm.

  • callback - se invoca para devolver los resultados.

Devuelve

un RealmAsyncTask que representa una tarea cancelable.

Throws

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.

Parámetros

Devuelve

number of open Realm instances on the caller thread.

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

getSchema in class BaseRealm

public static synchronized 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 android.app.Application subclass:

public class MyApplication extends Application {
@Override
public void onCreate() {
super.onCreate();
Realm.init(this, "MyApp/" + BuildConfig.VERSION_NAME);
}
}

Recuerda registrarlo en el archivo AndroidManifest.xml:

<?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>

Parámetros

  • context - the Application Context.

  • userAgent - string opcional definida por el usuario que se enviará al objeto Realm servidor como parte de un cabecera User-Agent cuando se establezca una sesión. Esta configuración no será utilizada por Reinos no sincronizados.

Throws

public static synchronized 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 android.app.Application subclass:

public class MyApplication extends Application {
@Override
public void onCreate() {
super.onCreate();
Realm.init(this);
}
}

Recuerda registrarlo en el archivo AndroidManifest.xml:

<?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>

Parámetros

  • context - the Application Context.

Throws

public void insert (
RealmModel object
)

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:

  • 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.

  • No creamos (ni devolvemos) un RealmObject gestionado para cada elemento

  • 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.

Parámetros

  • object -RealmObjects para insertar.

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:

  • 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.

  • No creamos (ni devolvemos) un RealmObject gestionado para cada elemento

  • 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.

Parámetros

  • objects -RealmObjects para insertar.

Throws

  • IllegalStateException - if the corresponding Realm is closed, called from an incorrect thread or not in a transaction.

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.

  • No creamos (ni devolvemos) un RealmObject gestionado para cada elemento

  • 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.

Parámetros

  • object -RealmObjects para insertar.

Throws

  • IllegalStateException - if the corresponding Realm is closed, called from an incorrect thread or not in a transaction.

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.

  • No creamos (ni devolvemos) un RealmObject gestionado para cada elemento

  • 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.

Parámetros

  • objects -RealmObjects para insertar.

Throws

public boolean isEmpty ()

Comprueba si este io.realm.Realm contiene algún objeto.

Devuelve

true si está vacío, @{code false} en caso contrario.

Anulaciones

isEmpty in class BaseRealm

public static void migrateRealm (
RealmConfiguration configuration,
RealmMigration migration
)

Activa manualmente una migración en un RealmMigration.

Parámetros

  • configuration - la:ref:RealmConfiguration <io_realm_RealmConfiguration> .

  • migration - the RealmMigration to run on the Realm. This will override any migration set on the configuration.

Throws

public static void migrateRealm (
RealmConfiguration configuration
)

Manually triggers the migration associated with a given RealmConfiguration. If Realm is already at the latest version, nothing will happen.

Parámetros

Throws

Removes all user-defined change listeners.

Throws

Removes the specified change listener.

Parámetros

  • listener - the change listener to be removed.

Throws

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) .

public static void setDefaultConfiguration (
RealmConfiguration configuration
)

Establece la io.realm.RealmConfiguration que se utiliza al llamar a getDefaultInstance() .

Parámetros

Throws

Devuelve un RealmQuery tipado, que puede usarse para buscar objetos específicos de este tipo

Parámetros

  • clazz - la clase del objeto que se va a consultar.

Devuelve

a typed RealmQuery, which can be used to query for specific objects of this type.

Volver

Estado del proxy