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 RealmList

java.lang.Object

Implemented interfaces:

RealmList is used to model one-to-many relationships in a io.realm.RealmObject . RealmList has two modes: A managed and unmanaged mode. In managed mode all objects are persisted inside a Realm, in unmanaged mode it works as a normal ArrayList.

Only Realm can create managed RealmLists. Managed RealmLists will automatically update the content whenever the underlying Realm is updated, and can only be accessed using the getter of a io.realm.RealmObject .

El usuario puede crear listas de dominios no administradas que contengan objetos de dominio administrados y no administrados. Esto resulta útil al trabajar con deserializadores JSON como GSON u otros frameworks que inyectan valores en una clase. Los elementos no administrados de esta lista se pueden agregar a un dominio mediante el método Realm.copyToRealm(Iterable, ImportFlag...).

RealmList puede contener más elementos que Integer.MAX_VALUE En ese caso, solo podrá acceder a los primeros Integer.MAX_VALUE elementos.

Constructor and Description

Crea una RealmList en modo no gestionado, donde los elementos no están controlados por un Realm.

E[] objects
)

Creates a RealmList in unmanaged mode with an initial list of elements.

Modificador y Tipo
Campo y Descripción

public final BaseRealm

baseRealm

The BaseRealm instance in which this list resides.

Warning: This field is only exposed for internal usage, and should not be used.

Modificador y Tipo
Método y descripción

public booleano

add (
E object
)

Adds the specified object at the end of this List.

public void

add (
int location,
E element
)

Inserts the specified object into this List at the specified location.

public void

public void

public <any>

Returns an Rx Observable that monitors changes to this RealmList.

public <any>

Devuelve un Rx Flowable que monitorea los cambios en esta RealmList.

public double

String fieldName
)

Devuelve el promedio de un campo dado.

public void

Removes all elements from this list, leaving it empty.

public booleano

Object object
)

Devuelve true si la lista contiene el elemento especificado cuando se adjunta a un Realm.

Creates a snapshot from this OrderedRealmCollection .

public booleano

This deletes all objects in the collection from the underlying Realm as well as from the collection.

public booleano

Deletes the first object from the Realm.

public void

int location
)

Deletes the object at the given index from the Realm.

public booleano

Elimina el último objeto del Reino.

public E

E defaultValue
)

Gets the first object from the collection.

public E

Gets the first object from the collection.

public RealmList

public E

get (
int location
)

Returns the element at the specified location in this list.

public Realm

Devuelve la instancia de Realm a la que pertenece esta colección.

public booleano

public booleano

Checks if a collection has finished loading its data yet.

public booleano

Checks if the collection is managed by Realm.

public booleano

Checks if the collection is still valid to use, i.e., the io.realm.Realm instance hasn't been closed.

public Iterator

public E

E defaultValue
)

Gets the last object from the collection.

public E

last ()

Gets the last object from the collection.

int location
)

public booleano

load ()

Bloquea la recopilación hasta que todos los datos estén disponibles.

public Number

max (
String fieldName
)

Finds the maximum value of a field.

public Date

String fieldName
)

Encuentra la fecha máxima.

public Number

min (
String fieldName
)

Finds the minimum value of a field.

public Date

String fieldName
)

Finds the minimum date.

public void

int oldPos,
int newPos
)

Mueve un objeto de una posición a otra, manteniendo una lista de tamaño fijo.

public booleano

Object object
)

Removes one instance of the specified object from this Collection if one is contained.

public E

int location
)

Removes the object at the specified location from this list.

public booleano

Removes all occurrences in this Collection of each object in the specified Collection .

public void

Removes all user-defined change listeners.

public void

Removes the specified change listener.

public void

public E

set (
int location,
E object
)

Reemplaza el elemento en la ubicación especificada en esta lista con el objeto especificado.

public int

size ()

Returns the number of elements in this List .

java.lang.String[] fieldNames,
io.realm.Sort[] sortOrders
)

Ordena una colección en función de los campos y órdenes de clasificación enviados.

String fieldName1,
Sort sortOrder1,
String fieldName2,
Sort sortOrder2
)

Ordena una colección en función de los campos y órdenes de clasificación enviados.

String fieldName,
Sort sortOrder
)

Sorts a collection based on the provided field and sort order.

String fieldName
)

Ordena una colección según el campo proporcionado en orden ascendente.

public Number

sum (
String fieldName
)

Calculates the sum of a given field.

public String

Returns a RealmQuery, which can be used to query for specific objects of this class.

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

  • Methods inherited from class java.util.AbstractCollection : iterator , size , isEmpty , contains , toArray , toArray , add , remove , containsAll , addAll , removeAll , retainAll , clear , toString

  • Methods inherited from class java.util.AbstractList : add , get , set , add , remove , indexOf , lastIndexOf , clear , addAll , iterator , listIterator , listIterator , subList , equals , hashCode , removeRange

The BaseRealm instance in which this list resides.

Warning: This field is only exposed for internal usage, and should not be used.

public RealmList ()

Creates a RealmList in unmanaged mode, where the elements are not controlled by a Realm. This effectively makes the RealmList function as a java.util.ArrayList and it is not possible to query the objects in this state.

Utilice io.realm.Realm.copyToRealm(Iterable, ImportFlag...) para que sus elementos persistan correctamente en Realm.

public RealmList (
E[] objects
)

Creates a RealmList in unmanaged mode with an initial list of elements. A RealmList in unmanaged mode function as a java.util.ArrayList and it is not possible to query the objects in this state.

Utilice io.realm.Realm.copyToRealm(Iterable, ImportFlag...) para conservar correctamente todos los elementos no administrados en Realm.

Parámetros

  • objects - objetos iniciales en la lista.

public boolean add (
E object
)

Adds the specified object at the end of this List.

  1. RealmLists no gestionadas: Es posible añadir tanto objetos gestionados como no gestionados. Si se añaden objetos gestionados a una RealmList sin gestionar, no se copiarán de nuevo al Realm si se utiliza Realm.copyToRealm(RealmModel, ImportFlag...) posteriormente.

  2. Managed RealmLists: It is possible to add unmanaged objects to a RealmList that is already managed. In that case the object will transparently be copied to Realm using Realm.copyToRealm(RealmModel, ImportFlag...) or Realm.copyToRealmOrUpdate(RealmModel, ImportFlag...) if it has a primary key.

Parámetros

  • object - the object to add.

Devuelve

siempre true .

Throws

Anulaciones

add en la clase AbstractList

public void add (
int location,
E element
)

Inserts the specified object into this List at the specified location. The object is inserted before any previous element at the specified location. If the location is equal to the size of this List, the object is added at the end.

  1. RealmLists no gestionadas: Es posible añadir tanto objetos gestionados como no gestionados. Si se añaden objetos gestionados a una RealmList sin gestionar, no se copiarán de nuevo al Realm si se utiliza Realm.copyToRealm(RealmModel, ImportFlag...) posteriormente.

  2. Managed RealmLists: It is possible to add unmanaged objects to a RealmList that is already managed. In that case the object will transparently be copied to Realm using Realm.copyToRealm(RealmModel, ImportFlag...) or Realm.copyToRealmOrUpdate(RealmModel, ImportFlag...) if it has a primary key.

Parámetros

  • location - the index at which to insert.

  • element - el elemento a añadir.

Throws

Anulaciones

add en la clase AbstractList

Agrega un listener de cambios a este RealmList .

Registrar un detector de cambios no impedirá que la RealmList subyacente sea objeto de recolección de basura. Si se realiza la recolección de basura de la RealmList, 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 RealmList<Dog> dogs; // Strong reference to keep listeners alive
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
dogs = realm.where(Person.class).findFirst().getDogs();
dogs.addChangeListener(new RealmChangeListener<RealmList<Dog>>() {
@Override
public void onChange(RealmList<Dog> dogs) {
// React to change
}
});
}
}

Parámetros

  • listener - the change listener to be notified.

Throws

Agrega un listener de cambios a este RealmList .

Registrar un detector de cambios no impedirá que la RealmList subyacente sea objeto de recolección de basura. Si se realiza la recolección de basura de la RealmList, 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 RealmList<Dog> dogs; // Strong reference to keep listeners alive
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
dogs = realm.where(Person.class).findFirst().getDogs();
dogs.addChangeListener(new OrderedRealmCollectionChangeListener<RealmList<Dog>>() {
@Override
public void onChange(RealmList<Dog> dogs, OrderedCollectionChangeSet changeSet) {
// React to change
}
});
}
}

Parámetros

  • listener - the change listener to be notified.

Throws

public <any> asChangesetObservable ()

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

RealmList will continually be emitted as the RealmList 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:

list.asChangesetObservable()
.observeOn(Schedulers.computation())
.map((rxList, changes) -> doExpensiveWork(rxList, changes))
.observeOn(AndroidSchedulers.mainThread())
.subscribe( ... );

Devuelve

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

Throws

Tip

public <any> asFlowable ()

Returns an Rx Flowable that monitors changes to this RealmList. It will emit the current RealmList when subscribed to. RealmList will continually be emitted as the RealmList is updated - onComplete will never be called.

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 RealmList. This means that if you need to do further processing, it is recommend to observe the values on a computation scheduler:

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

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

Throws

  • UnsupportedOperationException - if the required RxJava framework is not on the classpath or the corresponding Realm instance doesn't support RxJava.

public double average (
String fieldName
)

Devuelve el promedio de un campo dado.

Devuelve

el promedio del campo indicado entre los objetos de los resultados de la query. Esto será del tipo double para todos los campos de tipo numérico. Si no existen objetos o todos tienen null como valor para el campo dado, 0 será devuelto. Al calcular el promedio, se ignoran los objetos con valores null.

public void clear ()

Remueve todos los elementos de esta lista, dejándola vacía. Este método no remueve los objetos del Realm.

Throws

Anulaciones

clear en la clase AbstractList

public boolean contains (
Object object
)

Returns true if the list contains the specified element when attached to a Realm. This method will query the native Realm underlying storage engine to quickly find the specified element.

If the list is not attached to a Realm, the default List.contains(Object) implementation will occur.

Parámetros

  • object - the element whose presence in this list is to be tested.

Devuelve

true si esta lista contiene el elemento especificado; de lo contrario, false .

Anulaciones

contains en la clase AbstractCollection

Creates a snapshot from this OrderedRealmCollection .

Devuelve

the snapshot of this collection.

public boolean deleteAllFromRealm ()

This deletes all objects in the collection from the underlying Realm as well as from the collection.

Devuelve

true si se borraron objetos, false de lo contrario.

public boolean deleteFirstFromRealm ()

Deletes the first object from the Realm. This also removes it from this collection.

Devuelve

true if an object was deleted, false otherwise.

public void deleteFromRealm (
int location
)

Deletes the object at the given index from the Realm. This also removes it from the collection.

public boolean deleteLastFromRealm ()

Elimina el último objeto del dominio. Esto también lo elimina de esta colección.

Devuelve

true if an object was deleted, false otherwise.

public E first (
E defaultValue
)

Gets the first object from the collection. If the collection is empty, the provided default will be used instead.

Devuelve

the first object or the provided default.

public E first ()

Gets the first object from the collection.

Devuelve

the first object.

public RealmList freeze ()

public E get (
int location
)

Returns the element at the specified location in this list.

Parámetros

  • location - el índice del elemento a devolver.

Devuelve

the element at the specified index.

Throws

Anulaciones

get en la clase AbstractList

public Realm getRealm ()

Devuelve la instancia de Realm a la que pertenece esta colección.

Calling Realm.close() on the returned instance is discouraged as it is the same as calling it on the original Realm instance which may cause the Realm to fully close invalidating the list.

Devuelve

Realm instance this collection belongs to or null if the collection is unmanaged.

Throws

public boolean isFrozen ()

public boolean isLoaded ()

Checks if a collection has finished loading its data yet.

Devuelve

true if data has been loaded and is available, false if data is still being loaded.

public boolean isManaged ()

Checks if the collection is managed by Realm. A managed collection is just a wrapper around the data in the underlying Realm file. On Looper threads, a managed collection will be live-updated so it always points to the latest data. Managed collections are thread confined so that they cannot be accessed from other threads than the one that created them.If this method returns false , the collection is unmanaged. An unmanaged collection is just a normal java collection, so it will not be live updated.

Devuelve

true if this is a managed RealmCollection , false otherwise.

public boolean isValid ()

Checks if the collection is still valid to use, i.e., the io.realm.Realm instance hasn't been closed. It will always return true for an unmanaged collection.

Devuelve

true if it is still valid to use or an unmanaged collection, false otherwise.

public Iterator iterator ()

Anulaciones

iterator en la clase AbstractList

public E last (
E defaultValue
)

Gets the last object from the collection. If the collection is empty, the provided default will be used instead.

Devuelve

the last object or the provided default.

public E last ()

Gets the last object from the collection.

Devuelve

the last object.

int location
)

Anulaciones

listIterator en la clase AbstractList

Anulaciones

listIterator en la clase AbstractList

public boolean load ()

Bloquea la recopilación hasta que todos los datos estén disponibles.

Devuelve

true si los datos se pudieran cargar correctamente, false de lo contrario.

public Number max (
String fieldName
)

Finds the maximum value of a field.

Devuelve

si no existen objetos o todos tienen null como valor para el campo dado, se devolverá null. En caso contrario, se devuelve el valor máximo. Al determinar el valor máximo, se ignoran los objetos con valores null.

public Date maxDate (
String fieldName
)

Encuentra la fecha máxima.

Devuelve

Si no existen objetos o si todos tienen null como valor para el campo de fecha dado, se devolverá null. De lo contrario, se devuelve la fecha máxima. Al determinar la fecha máxima, los objetos con valores null se ignoran.

public Number min (
String fieldName
)

Finds the minimum value of a field.

Devuelve

si no existen objetos o todos tienen null como valor para el campo dado, se devolverá null. De lo contrario, se devuelve el valor mínimo. Al determinar el valor mínimo, se ignoran los objetos con valores null.

public Date minDate (
String fieldName
)

Finds the minimum date.

Devuelve

if no objects exist or they all have null as the value for the given date field, null will be returned. Otherwise the minimum date is returned. When determining the minimum date, objects with null values are ignored.

public void move (
int oldPos,
int newPos
)

Mueve un objeto de una posición a otra, manteniendo una lista de tamaño fijo. Los RealmObjects se desplazarán para que no se introduzcan valores null.

Parámetros

  • oldPos - index of RealmObject to move.

  • newPos - posición objetivo. Si newPos < oldPos, el objeto en la ubicación se moverá a la derecha. Si oldPos < newPos, los índices > oldPos se desplazarán una vez a la izquierda.

Throws

public boolean remove (
Object object
)

Elimina una instancia del objeto especificado de este Collection si contiene una. Esta implementación itera sobre este Collection y comprueba cada elemento e devuelto por el iterador para determinar si e es igual al objeto dado. Si es object != null, esta comprobación se realiza mediante object.equals(e) ; de lo contrario, mediante object == null . Si se encuentra un elemento igual al objeto dado, se llama al método remove en el iterador y se devuelve true; en caso contrario, se devuelve false. Si el iterador no admite la eliminación de elementos, se lanza un UnsupportedOperationException.

Parámetros

  • object - el objeto a eliminar.

Devuelve

true si se modifica este Collection, false en caso contrario.

Throws

Anulaciones

remove en la clase AbstractCollection

public E remove (
int location
)

Removes the object at the specified location from this list.

Parámetros

  • location - the index of the object to remove.

Devuelve

the removed object.

Throws

Anulaciones

remove en la clase AbstractList

public boolean removeAll (
)

Elimina todas las ocurrencias en este Collection de cada objeto en el Collection ​​especificado. Después de que este método retorna, ninguno de los elementos en el Collection pasado se puede encontrar en este Collection.

Esta implementación itera sobre el Collection y comprueba cada elemento e devuelto por el iterador, si está contenido en el Collection especificado. Si esta prueba es positiva, entonces el método remove se llama en el iterador.

Parámetros

  • collection - the collection of objects to remove.

Devuelve

true si se modifica este Collection, false en caso contrario.

Throws

Anulaciones

removeAll en la clase AbstractCollection

Removes all user-defined change listeners.

Throws

Removes the specified change listener.

Parámetros

  • listener - the change listener to be removed.

Throws

Removes the specified change listener.

Parámetros

  • listener - the change listener to be removed.

Throws

public E set (
int location,
E object
)

Reemplaza el elemento en la ubicación especificada en esta lista con el objeto especificado.

  1. RealmLists no gestionadas: Es posible añadir tanto objetos gestionados como no gestionados. Si se añaden objetos gestionados a una RealmList sin gestionar, no se copiarán de nuevo al Realm si se utiliza Realm.copyToRealm(RealmModel, ImportFlag...) posteriormente.

  2. Managed RealmLists: It is possible to add unmanaged objects to a RealmList that is already managed. In that case the object will transparently be copied to Realm using Realm.copyToRealm(RealmModel, ImportFlag...) or Realm.copyToRealmOrUpdate(RealmModel, ImportFlag...) if it has a primary key.

Parámetros

  • location - the index at which to put the specified object.

  • object - the object to add.

Devuelve

el elemento anterior en el índice.

Throws

Anulaciones

set en la clase AbstractList

public int size ()

Returns the number of elements in this List .

Devuelve

El número de elementos en este List .

Throws

Anulaciones

size en la clase AbstractCollection

java.lang.String[] fieldNames,
io.realm.Sort[] sortOrders
)

Ordena una colección en función de los campos y órdenes de clasificación enviados.

Devuelve

se creará y devolverá un nuevo RealmResults ordenado. La colección original permanece sin cambios.

String fieldName1,
Sort sortOrder1,
String fieldName2,
Sort sortOrder2
)

Ordena una colección en función de los campos y órdenes de clasificación enviados.

Devuelve

se creará y devolverá un nuevo RealmResults ordenado. La colección original permanece sin cambios.

String fieldName,
Sort sortOrder
)

Sorts a collection based on the provided field and sort order.

Devuelve

se creará y devolverá un nuevo RealmResults ordenado. La colección original permanece sin cambios.

String fieldName
)

Ordena una colección según el campo proporcionado en orden ascendente.

Devuelve

se creará y devolverá un nuevo RealmResults ordenado. La colección original permanece sin cambios.

public Number sum (
String fieldName
)

Calculates the sum of a given field.

Devuelve

la suma. Si no existen objetos o todos tienen null como valor para el campo dado, se devolverá 0. A la hora de calcular la suma, se ignoran los objetos con valores null.

public String toString ()

Anulaciones

toString en la clase AbstractCollection

public RealmQuery where ()

Returns a RealmQuery, which can be used to query for specific objects of this class.

Devuelve

un objeto de RealmQuery.

Throws

Volver

RealmFieldType