Make the MongoDB docs better! We value your opinion. Share your feedback for a chance to win $100.
Click here >
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

  • Any RealmObject subclass

  • 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

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.

public static void

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

public final void

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.

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
)

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

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

Adds a change listener to a RealmObject to get detailed information about the 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

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

Returns an Rx Observable that monitors changes to this RealmObject. It will emit the current RealmObject when subscribed to. For each update to the RealmObject a pair consisting of the RealmObject and the ObjectChangeSet will be sent. The changeset will be null the first time the RealmObject is emitted.

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 - RealmObject class that is being observed. Must be this class or its super types.

Devuelve

RxJava Observable that only calls onNext . It will never call onComplete or OnError .

Throws

public final <any> asChangesetObservable <E >()

Returns an Rx Observable that monitors changes to this RealmObject. It will emit the current RealmObject when subscribed to. For each update to the RealmObject a pair consisting of the RealmObject and the ObjectChangeSet will be sent. The changeset will be null the first time the RealmObject is emitted.

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

RxJava Observable that only calls onNext . It will never call onComplete or 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 .

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

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

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 - RealmObject class that is being observed. Must be this class or its super types.

Devuelve

RxJava Observable that only calls onNext . It will never call onComplete or 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 .

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

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

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 - RealmObject class that is being observed. Must be this class or its super types.

Devuelve

RxJava Observable that only calls onNext . It will never call onComplete or OnError .

Throws

public static void deleteFromRealm <E >(
E object
)

Deletes the object from the Realm it is currently associated with.After this method is called the object will be invalid and any operation (read or write) performed on it will fail with an IllegalStateException.

Throws

public final void deleteFromRealm ()

Deletes the object from the Realm it is currently associated to.After this method is called the object will be invalid and any operation (read or write) performed on it will fail with an 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.

Frozen objects can be queried as normal, but trying to mutate it in any way or attempting to register a listener will throw an 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.

Frozen objects can be queried as normal, but trying to mutate it in any way or attempting to register a listener will throw an 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 to check.

Devuelve

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

public final boolean isLoaded ()

Checks if the query used to find this RealmObject has completed.Async methods like RealmQuery.findFirstAsync() return a 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();
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
)

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. It will always return true for unmanaged objects.

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

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. It will always return true for unmanaged objects.

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 - the instance to be removed.

Throws

public static void removeChangeListener <E >(
)

Removes a previously registered listener on the given RealmObject.

Parámetros

  • object - RealmObject to remove listener from.

  • listener - the instance to be removed.

Throws

Removes a previously registered listener.

Parámetros

  • listener - the instance to be removed.

Throws

Removes a previously registered listener.

Parámetros

  • listener - the instance to be removed.

Throws

Volver

RealmModel

En esta página