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 DynamicRealm

java.lang.Object
io.realm.BaseRealm
io.realm.DynamicRealm

DynamicRealm es una variante dinámica de io.realm.Realm. Esto significa que todo acceso a los datos y/o consultas se realiza utilizando nombres de clase basados en cadenas en lugar de referencias a tipos de clase.

This is useful during migrations or when working with string-based data like CSV or XML files.

La misma io.realm.RealmConfiguration puede usarse para abrir un archivo Realm tanto en modo dinámico como tipificado, pero modificar el esquema mientras hay una versión tipificada y dinámica abierta no es recomendado y muy probablemente provocará un fallo en el Realm tipificado. Durante las migraciones, solo un DynamicRealm estará abierto.

Los Reinos Dinámicos no aplican esquemas ni versiones de esquemas, y el código RealmMigration no se utiliza aunque se haya definido en la RealmConfiguration .

Esto significa que el esquema no se crea ni se valida hasta que se abre un dominio en modo tipificado. Si un archivo de dominio se abre primero en modo dinámico, no contendrá información sobre clases y campos, y cualquier consulta a las clases definidas por el esquema fallará.

Tip

  • Realm

  • RealmSchema

Modificador y Tipo
Clase y descripción

public static interface

public abstract static

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.

objeto público de DynamicRealmObject

String className,
DynamicRealmObject parentObject,
String parentProperty
)

Instantiates and adds a new embedded object to the Realm.

objeto público de DynamicRealmObject

String className,
Object primaryKeyValue
)

Crea un objeto con una clave principal determinada.

objeto público de DynamicRealmObject

String className
)

Instantiates and adds a new object to the Realm.

public void

String className
)

Deletes all objects of the specified class from the Realm.

public void

Ejecuta una transacción determinada en el DynamicRealm.

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.

Returns a frozen snapshot of the current Realm.

public static DynamicRealm

Constructor estático de Realm que devuelve una instancia Realm dinámica de la instancia definida por io.realm.RealmConfiguration proporcionado.

public static RealmAsyncTask

La creación de la primera instancia Realm por RealmConfiguration en un proceso puede tomar algún tiempo ya que todo el código de inicialización necesita ejecutarse en ese punto (configuración del Realm, validación de esquemas y creación de datos iniciales).

Returns the mutable schema for this Realm.

public booleano

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

public void

Removes all user-defined change listeners.

public void

Removes the specified change listener.

String className
)

Devuelve un RealmQuery, que se puede utilizar para consultar la clase proporcionada.

  • 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

Adds a change listener to the Realm.The listeners will be executed when changes are committed by this or another thread.

Realm instances are cached per thread. For that reason it is important to remember to remove listeners again either using removeChangeListener(RealmChangeListener) or removeAllChangeListeners() . Not doing so can cause memory leaks.

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

String className,
DynamicRealmObject 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

  • className - the class name of the object to create.

  • parentObject - El objeto principal que debe tener una referencia al objeto incrustado. Si la propiedad principal es una lista, el objeto incrustado se añadirá al final de esa lista.

  • parentProperty - the property in the parent class which holds the reference.

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.

String className,
Object primaryKeyValue
)

Creates an object with a given primary key. Classes without a primary key defined must use createObject(String) } instead.

Devuelve

el nuevo objeto. Todos los campos tendrán valores por defecto para su tipo, excepto el campo de llave primaria que tendrá el valor proporcionado.

Throws

Instantiates and adds a new object to the Realm.

Parámetros

  • className - the class name of the object to create.

Devuelve

the new object.

Throws

public void delete (
String className
)

Deletes all objects of the specified class from the Realm.

Parámetros

  • className - the class for which all objects should be removed.

Throws

Ejecuta una transacción en DynamicRealm. Las operacionesbeginTransaction() y commitTransaction() se invocan automáticamente. Si se lanza una excepción durante la transacción, se invocará cancelTransaction() en lugar de 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 - 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

  • transaction - Transaction to execute.

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

Parámetros

  • transaction - Transaction to execute.

  • onSuccess - callback invoked when the transaction succeeds.

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

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 DynamicRealm getInstance (
RealmConfiguration configuration
)

Realm static constructor that returns a dynamic variant of the Realm instance defined by provided io.realm.RealmConfiguration . Dynamic Realms do not care about schemaVersion and schemas, so opening a DynamicRealm will never trigger a migration.

Devuelve

el DynamicRealm definido por la configuración.

Throws

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

Returns the mutable schema for this Realm.

Devuelve

The RealmSchema for this Realm.

Anulaciones

getSchema in class BaseRealm

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

Removes all user-defined change listeners.

Throws

Removes the specified change listener.

Parámetros

  • listener - the change listener to be removed.

Throws

public RealmQuery where (
String className
)

Devuelve un RealmQuery, que se puede utilizar para consultar la clase proporcionada.

Parámetros

  • className - the class of the object which is to be queried.

Devuelve

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

Throws

Volver

Devolución de llamada predeterminada CompactOnLaunch

En esta página