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

Clase RealmObject

java.lang.Object
io.realm.RealmObject

Implemented interfaces:

  • io.realm.RealmModel

In Realm you define your RealmObject classes by sub-classing RealmObject and adding fields to be persisted. You then create your objects within a Realm, and use your custom subclasses instead of using the RealmObject class directly.An annotation processor will create a proxy class for your RealmObject subclass.

The following field data types are supported:

  • boolean/Boolean

  • short/Short

  • int/Entero

  • largo/Largo

  • float/Float

  • double/Double

  • byte[]

  • String

  • fecha

  • UUID

  • org.bson.types.Decimal128

  • org.bson.types.ObjectId

  • Cualquier subclase de RealmObject

  • RealmList

  • RealmDictionary

Los tipos short , int y long se asignan a long cuando se almacenan dentro de un reino.

La única restricción que tiene un RealmObject es que no se permite que los campos sean finales o volátiles. Está permitido cualquier método, así como campos públicos. Al proporcionar constructores personalizados, se debe declarar un constructor público sin argumentos.

Los campos anotados con io.realm.annotations.Ignore no tienen estas restricciones y no requieren un getter ni un setter.

Realm will create indexes for fields annotated with io.realm.annotations.Index . This will speedup queries but will have a negative impact on inserts and updates.

No se puede pasar un RealmObject entre diferentes hilos.

Tip

Constructor and Description
Modificador y Tipo
Método y descripción

public static void

Agrega un detector de cambios a un RealmObject que se activará si se modifica algún campo de valor o un campo RealmObject referenciado, o si se modifica el campo RealmList en sí.

public static void

Adds a change listener to a RealmObject to get detailed information about the changes.

public final void

Agrega un detector de cambios a este RealmObject que se activará si se modifica algún campo de valor o un campo RealmObject referenciado, o si se modifica el campo RealmList en sí.

public final void

Adds a change listener to this RealmObject to get detailed information about changes.

public static <any>

E object
)

Returns an Rx Observable that monitors changes to this RealmObject.

public final <any>

Returns an Rx Observable that monitors changes to this RealmObject.

public static <any>

E object
)

Returns an RxJava Flowable that monitors changes to this RealmObject.

public final <any>

asFlowable <E >()

Returns an RxJava Flowable that monitors changes to this RealmObject.

public static void

E object
)

Elimina el objeto del reino con el que está asociado actualmente.

public final void

Deletes the object from the Realm it is currently associated to.

public static E

freeze <E >(
E object
)

Returns a frozen snapshot of this object.

public final E

freeze <E >()

Returns a frozen snapshot of this object.

public static Realm

returns Realm instance where the model belongs.

public Realm

Devuelve la instancia Realm a la que pertenece este RealmObject.

public static boolean

isFrozen <E >(
E object
)

Indica si este RealmObject está congelado o no.

public final boolean

Indica si este RealmObject está congelado o no.

public static boolean

isLoaded <E >(
E object
)

Verifica si la query utilizada para encontrar este RealmObject se ha completado.

public final boolean

Verifica si la query utilizada para encontrar este RealmObject se ha completado.

public static boolean

isManaged <E >(
E object
)

Checks if this object is managed by Realm.

public booleano

Checks if this object is managed by Realm.

public static boolean

isValid <E >(
E object
)

Checks if the RealmObject is still valid to use i.e., the RealmObject hasn't been deleted nor has the io.realm.Realm been closed.

public final boolean

Checks if the RealmObject is still valid to use i.e., the RealmObject hasn't been deleted nor has the io.realm.Realm been closed.

public static boolean

load <E >(
E object
)

Makes an asynchronous query blocking.

public final boolean

load ()

Makes an asynchronous query blocking.

public static void

Removes all registered listeners from the given RealmObject.

public final void

Removes all registered listeners.

public static void

Removes a previously registered listener on the given RealmObject.

public static void

Removes a previously registered listener on the given RealmObject.

public final void

Removes a previously registered listener.

public final void

Removes a previously registered listener.

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

public RealmObject ()

public static void addChangeListener <E >(
)

Adds a change listener to a RealmObject that will be triggered if any value field or referenced RealmObject field is changed, or the RealmList field itself is changed.Registering a change listener will not prevent the underlying RealmObject from being garbage collected. If the RealmObject is garbage collected, the change listener will stop being triggered. To avoid this, keep a strong reference for as long as appropriate e.g. in a class variable.

public class MyActivity extends Activity {
private Person person; // Strong reference to keep listeners alive
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
person = realm.where(Person.class).findFirst();
person.addChangeListener(new RealmChangeListener<Person>() {
@Override
public void onChange(Person person) {
// React to change
}
});
}
}

Parámetros

  • object - RealmObject to add listener to.

  • listener - the change listener to be notified.

Throws

public static void addChangeListener <E >(
)

Añade un detector de cambios a un RealmObject para obtener información detallada sobre los cambios. El detector se activará si se modifica algún campo de valor, un campo RealmObject referenciado o el propio campo RealmList. Registrar un detector de cambios no impedirá que el RealmObject subyacente sea objeto de recolección de basura. Si el RealmObject es objeto de recolección de basura, el detector de cambios dejará de activarse. Para evitar esto, mantenga una referencia fuerte durante el tiempo que sea necesario, por ejemplo, en una variable de clase.

public class MyActivity extends Activity {
private Person person; // Strong reference to keep listeners alive
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
person = realm.where(Person.class).findFirst();
person.addChangeListener(new RealmObjectChangeListener<Person>() {
@Override
public void onChange(Person person, ObjectChangeSet changeSet) {
// React to change
}
});
}
}

Parámetros

  • object - RealmObject to add listener to.

  • listener - the change listener to be notified.

Throws

public final void addChangeListener <E >(
)

Adds a change listener to this RealmObject that will be triggered if any value field or referenced RealmObject field is changed, or the RealmList field itself is changed.Registering a change listener will not prevent the underlying RealmObject from being garbage collected. If the RealmObject is garbage collected, the change listener will stop being triggered. To avoid this, keep a strong reference for as long as appropriate e.g. in a class variable.

public class MyActivity extends Activity {
private Person person; // Strong reference to keep listeners alive
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
person = realm.where(Person.class).findFirst();
person.addChangeListener(new RealmChangeListener<Person>() {
@Override
public void onChange(Person person) {
// React to change
}
});
}
}

Parámetros

  • listener - the change listener to be notified.

Throws

Adds a change listener to this RealmObject to get detailed information about changes. The listener will be triggered if any value field or referenced RealmObject field is changed, or the RealmList field itself is changed.Registering a change listener will not prevent the underlying RealmObject from being garbage collected. If the RealmObject is garbage collected, the change listener will stop being triggered. To avoid this, keep a strong reference for as long as appropriate e.g. in a class variable.

public class MyActivity extends Activity {
private Person person; // Strong reference to keep listeners alive
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
person = realm.where(Person.class).findFirst();
person.addChangeListener(new RealmObjectChangeListener<Person>() {
@Override
public void onChange(Person person, ObjectChangeSet changeSet) {
// React to change
}
});
}
}

Parámetros

  • listener - the change listener to be notified.

Throws

public static <any> asChangesetObservable <E >(
E object
)

Devuelve un Observable Rx que monitoriza los cambios en este RealmObject. Emitirá el RealmObject actual al suscribirse. Por cada actualización del RealmObject, se enviará un par compuesto por el RealmObject y el ObjectChangeSet. El conjunto de cambios será null la primera vez que se emita el RealmObject.

The RealmObject will continually be emitted as it is updated - onComplete will never be called.

Los elementos emitidos por Realm Observables están congelados (consulta freeze() ). Esto significa que son inmutables y se pueden leer en cualquier hilo.

Realm Observables 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:

obj.asChangesetObservable()
.observeOn(Schedulers.computation())
.map((rxObj, changes) -> doExpensiveWork(rxObj, changeså))
.observeOn(AndroidSchedulers.mainThread())
.subscribe( ... );

Parámetros

  • object Clase RealmObject que se observa. Debe ser esta clase o sus supertipos.

Devuelve

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

Throws

public final <any> asChangesetObservable <E >()

Devuelve un Observable Rx que monitoriza los cambios en este RealmObject. Emitirá el RealmObject actual al suscribirse. Por cada actualización del RealmObject, se enviará un par compuesto por el RealmObject y el ObjectChangeSet. El conjunto de cambios será null la primera vez que se emita el RealmObject.

The RealmObject will continually be emitted as it is updated - onComplete will never be called.

Los elementos emitidos por Realm Observables están congelados (consulta freeze() ). Esto significa que son inmutables y se pueden leer en cualquier hilo.

Realm Observables 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:

obj.asChangesetObservable()
.observeOn(Schedulers.computation())
.map((rxObj, changes) -> doExpensiveWork(rxObj, changeså))
.observeOn(AndroidSchedulers.mainThread())
.subscribe( ... );

Devuelve

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

Throws

public static <any> asFlowable <E >(
E object
)

Returns an RxJava Flowable that monitors changes to this RealmObject. It will emit the current object when subscribed to. Object updates will continuously be emitted as the RealmObject is updated - onComplete will never be called.

When chaining a RealmObject observable use obj.<MyRealmObjectClass>asFlowable() to pass on type information, otherwise the type of the following observables will be RealmObject .

Los elementos emitidos desde Realm Flowables están congelados (ver freeze()). Esto significa que son inmutables y se pueden leer en cualquier hilo.

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:

obj.asFlowable()
.observeOn(Schedulers.computation())
.map((rxObj) -> doExpensiveWork(rxObj))
.observeOn(AndroidSchedulers.mainThread())
.subscribe( ... );

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

obj.asFlowable()
.filter(obj -> obj.isLoaded())
.first()
.subscribe( ... ) // You only get the object once

Parámetros

  • object Clase RealmObject que se observa. Debe ser esta clase o sus supertipos.

Devuelve

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

Throws

public final <any> asFlowable <E >()

Devuelve un RxJava Flowable que supervisa cambios en este RealmObject. Emitirá el objeto actual cuando se suscriba. Las actualizaciones de los objetos se emitirán continuamente a medida que se actualice el RealmObject - onComplete nunca se llamará.

When chaining a RealmObject flowable use obj.<MyRealmObjectClass>asFlowable() to pass on type information, otherwise the type of the following observables will be RealmObject .

Los elementos emitidos desde Realm Flowables están congelados (ver freeze()). Esto significa que son inmutables y se pueden leer en cualquier hilo.

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:

obj.asFlowable()
.observeOn(Schedulers.computation())
.map((rxObj) -> doExpensiveWork(rxObj))
.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:

obj.asFlowable()
.filter(obj -> obj.isLoaded())
.first()
.subscribe( ... ) // You only get the object once

Type Parameters

  • E Clase RealmObject que se observa. Debe ser esta clase o sus supertipos.

Devuelve

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

Throws

public static void deleteFromRealm <E >(
E object
)

Elimina el objeto del reino con el que está asociado actualmente. Después de llamar a este método, el objeto no será válido y cualquier operación (lectura o escritura) realizada en él fallará con una IllegalStateException.

Throws

public final void deleteFromRealm ()

Elimina el objeto del reino al que está asociado actualmente. Después de llamar a este método, el objeto no será válido y cualquier operación (lectura o escritura) realizada en él fallará con una IllegalStateException.

Throws

public static E freeze <E >(
E object
)

Returns a frozen snapshot of this object. The frozen copy can be read and queried from any thread without throwing an IllegalStateException .

La congelación de un RealmObject también crea un Realm congelado que tiene su propio ciclo de vida, pero si el Realm en vivo que generó la colección original se cierra completamente (es decir, todas las instancias de todos los hilos están cerradas), el Realm congelado y el objeto también se cerrarán.

Los objetos congelados se pueden consultar de forma normal, pero intentar mutarlos de cualquier forma o intentar registrar un oyente arrojará una IllegalStateException.

Nota: Mantener un gran número de objetos congelados con diferentes versiones activas 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 objeto.

Throws

public final E freeze <E >()

Returns a frozen snapshot of this object. The frozen copy can be read and queried from any thread without throwing an IllegalStateException .

La congelación de un RealmObject también crea un Realm congelado que tiene su propio ciclo de vida, pero si el Realm en vivo que generó la colección original se cierra completamente (es decir, todas las instancias de todos los hilos están cerradas), el Realm congelado y el objeto también se cerrarán.

Los objetos congelados se pueden consultar de forma normal, pero intentar mutarlos de cualquier forma o intentar registrar un oyente arrojará una IllegalStateException.

Nota: Mantener un gran número de objetos congelados con diferentes versiones activas 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 objeto.

Throws

public static Realm getRealm (
)

returns Realm instance where the model belongs.

You must not call Realm.close() against returned instance.

Parámetros

Devuelve

Realm instance where the model belongs or null if the model is unmanaged.

Throws

public Realm getRealm ()

Devuelve la instancia Realm a la que pertenece este RealmObject.

You must not call Realm.close() against returned instance.

Devuelve

Instancia de Realm a la que pertenece este objeto o null si este objeto no está gestionado.

Throws

public static boolean isFrozen <E >(
E object
)

Indica si este RealmObject está congelado o no.

Devuelve

true if the RealmObject is frozen, false if it is not.

public final boolean isFrozen ()

Indica si este RealmObject está congelado o no.

Devuelve

true if the RealmObject is frozen, false if it is not.

public static boolean isLoaded <E >(
E object
)

Checks if the query used to find this RealmObject has completed.Async methods like RealmQuery.findFirstAsync() return an RealmObject that represents the future result of the RealmQuery . It can be considered similar to a java.util.concurrent.Future in this regard.

Una vez que isLoaded() devuelva true , el objeto representa el resultado de la query incluso si la query no encontró ningún objeto que cumpla con los parámetros de la query. En este caso, el RealmObject se convertirá en un objeto "null".

"Null" objects represents null . An exception is throw if any accessor is called, so it is important to also check isValid() before calling any methods. A common pattern is:

Person person = realm.where(Person.class).findFirstAsync();
RealmObject.isLoaded(person); // == false
RealmObject.addChangeListener(person, new RealmChangeListener() {
@Override
public void onChange(Person person) {
RealmObject.isLoaded(person); // always true here
if (RealmObject.isValid(person)) {
// It is safe to access the person.
}
}
});

Synchronous RealmObjects are by definition blocking hence this method will always return true for them. This method will return true if called on an unmanaged object (created outside of Realm).

Parámetros

  • object -RealmObject a comprobar.

Devuelve

true si la consulta se ha completado, false si la consulta está en progreso.

public final boolean isLoaded ()

Comprueba si la consulta utilizada para encontrar este RealmObject se ha completado. Los métodos asíncronos como RealmQuery.findFirstAsync() devuelven un RealmObject que representa el resultado futuro de la RealmQuery. En este sentido, puede considerarse similar a java.util.concurrent.Future.

Una vez que isLoaded() devuelva true , el objeto representa el resultado de la query incluso si la query no encontró ningún objeto que cumpla con los parámetros de la query. En este caso, el RealmObject se convertirá en un objeto "null".

"Null" objects represents null . An exception is throw if any accessor is called, so it is important to also check isValid() before calling any methods. A common pattern is:

Person person = realm.where(Person.class).findFirstAsync();
person.isLoaded(); // == false
person.addChangeListener(new RealmChangeListener() {
@Override
public void onChange(Person person) {
person.isLoaded(); // Always true here
if (person.isValid()) {
// It is safe to access the person.
}
}
});

Synchronous RealmObjects are by definition blocking hence this method will always return true for them. This method will return true if called on an unmanaged object (created outside of Realm).

Devuelve

true si la consulta se ha completado, false si la consulta está en progreso.

public static boolean isManaged <E >(
E object
)

Verifica si este objeto es gestionado por Realm. Un objeto gestionado es solo un contenedor alrededor de los datos en el archivo Realm subyacente. En los Looper threads, un objeto gestionado se actualizará en vivo para que siempre apunte a los datos más recientes. Es posible registrar un oyente de cambios usando addChangeListener(RealmModel, RealmChangeListener) para recibir notificaciones cuando ocurran cambios. Los objetos gestionados están confinados a un hilo para que no se pueda acceder a ellos desde otros hilos que no sean el que los creó.

Si este método retorna false , el objeto no está gestionado. Un objeto no administrado es simplemente un objeto Java normal, por lo que se puede analizar libremente en todos los hilos, pero los datos en el objeto no están conectados al Realm subyacente, por lo que no se actualizarán en vivo.

It is possible to create a managed object from an unmanaged object by using Realm.copyToRealm(RealmModel, ImportFlag...) . An unmanaged object can be created from a managed object by using Realm.copyFromRealm(RealmModel) .

Devuelve

true si el objeto está gestionado, false si no lo está.

public boolean isManaged ()

Verifica si este objeto es gestionado por Realm. Un objeto gestionado es solo un contenedor alrededor de los datos en el archivo Realm subyacente. En los Looper threads, un objeto gestionado se actualizará en vivo para que siempre apunte a los datos más recientes. Es posible registrar un observador de cambios utilizando addChangeListener(RealmChangeListener) para recibir notificaciones cuando ocurran cambios. Los objetos gestionados están confinados a un hilo para que no se pueda acceder a ellos desde otros hilos que no sean el que los creó.

Si este método retorna false , el objeto no está gestionado. Un objeto no administrado es simplemente un objeto Java normal, por lo que se puede analizar libremente en todos los hilos, pero los datos en el objeto no están conectados al Realm subyacente, por lo que no se actualizarán en vivo.

It is possible to create a managed object from an unmanaged object by using Realm.copyToRealm(RealmModel, ImportFlag...) . An unmanaged object can be created from a managed object by using Realm.copyFromRealm(RealmModel) .

Devuelve

true si el objeto está gestionado, false si no lo está.

public static boolean isValid <E >(
E object
)

Comprueba si el objeto RealmObject sigue siendo válido, es decir, si no se ha eliminado ni se ha cerrado io.realm.Realm. Siempre devolverá true para objetos no administrados.

Parámetros

  • object - RealmObject to check validity for.

Devuelve

true if the object is still accessible or an unmanaged object, false otherwise.

public final boolean isValid ()

Comprueba si el objeto RealmObject sigue siendo válido, es decir, si no se ha eliminado ni se ha cerrado io.realm.Realm. Siempre devolverá true para objetos no administrados.

Note that this can be used to check the validity of certain conditions such as being null when observed.

realm.where(BannerRealm.class).equalTo("type", type).findFirstAsync().asFlowable()
.filter(result.isLoaded() && result.isValid())
.first()

Devuelve

true if the object is still accessible or an unmanaged object, false otherwise.

public static boolean load <E >(
E object
)

Makes an asynchronous query blocking. This will also trigger any registered listeners.Note: This will return true if called for an unmanaged object (created outside of Realm).

Parámetros

  • object - RealmObject to force load.

Devuelve

true if it successfully completed the query, false otherwise.

public final boolean load ()

Makes an asynchronous query blocking. This will also trigger any registered listeners.Note: This will return true if called for an unmanaged object (created outside of Realm).

Devuelve

true if it successfully completed the query, false otherwise.

public static void removeAllChangeListeners <E >(
E object
)

Removes all registered listeners from the given RealmObject.

Parámetros

  • object - RealmObject to remove all listeners from.

Throws

public final void removeAllChangeListeners ()

Removes all registered listeners.

public static void removeChangeListener <E >(
)

Removes a previously registered listener on the given RealmObject.

Parámetros

  • object - RealmObject to remove listener from.

  • listener - la instancia que se va a eliminar.

Throws

public static void removeChangeListener <E >(
)

Removes a previously registered listener on the given RealmObject.

Parámetros

  • object - RealmObject to remove listener from.

  • listener - la instancia que se va a eliminar.

Throws

Removes a previously registered listener.

Parámetros

  • listener - la instancia que se va a eliminar.

Throws

Removes a previously registered listener.

Parámetros

  • listener - la instancia que se va a eliminar.

Throws

Volver

Modelo de reino

En esta página