Package io.realm

Class RealmResults<E>

  • Type Parameters:
    E - The class of objects in this list.
    All Implemented Interfaces:
    io.realm.internal.Freezable<RealmCollection<E>>, io.realm.internal.ManageableObject, OrderedRealmCollection<E>, RealmCollection<E>, Iterable<E>, Collection<E>, List<E>

    public class RealmResults<E>
    extends AbstractList<E>
    This class holds all the matches of a RealmQuery for a given Realm. The objects are not copied from the Realm to the RealmResults list, but are just referenced from the RealmResult instead. This saves memory and increases speed.

    RealmResults are live views, which means that if it is on an Looper thread, it will automatically update its query results after a transaction has been committed. If on a non-looper thread, BaseRealm.refresh() must be called to update the results.

    Updates to RealmObjects from a RealmResults list must be done from within a transaction and the modified objects are persisted to the Realm file during the commit of the transaction.

    A RealmResults object cannot be passed between different threads.

    Notice that a RealmResults is never null not even in the case where it contains no objects. You should always use the List.size() method to check if a RealmResults is empty or not.

    If a RealmResults is built on RealmList through RealmList.where(), it will become empty when the source RealmList gets deleted.

    RealmResults can contain more elements than Integer.MAX_VALUE. In that case, you can access only first Integer.MAX_VALUE elements in it.

    See Also:
    RealmQuery.findAll(), Realm.executeTransaction(Realm.Transaction)
    • Field Detail

      • baseRealm

        public final io.realm.BaseRealm baseRealm
        The BaseRealm instance in which this collection resides.

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

    • Method Detail

      • where

        public RealmQuery<E> where()
        Returns a RealmQuery, which can be used to query for specific objects from this collection.
        Returns:
        a RealmQuery object.
        See Also:
        RealmQuery
      • sort

        public RealmResults<E> sort​(String fieldName1,
                                    Sort sortOrder1,
                                    String fieldName2,
                                    Sort sortOrder2)
        Sorts a collection based on the provided fields and sort orders.
        Specified by:
        sort in interface OrderedRealmCollection<E>
        Parameters:
        fieldName1 - first field name. Only fields of type boolean, short, int, long, float, double, Date, and String are supported.
        sortOrder1 - sort order for first field.
        fieldName2 - second field name. Only fields of type boolean, short, int, long, float, double, Date, and String are supported.
        sortOrder2 - sort order for second field.
        Returns:
        a new sorted RealmResults will be created and returned. The original collection stays unchanged.
      • isLoaded

        public boolean isLoaded()
        Returns false if the results are not yet loaded, true if they are loaded.
        Returns:
        true if the query has completed and the data is available, false if the query is still running in the background.
      • load

        public boolean load()
        Makes an asynchronous query blocking. This will also trigger any registered RealmChangeListener when the query completes.
        Returns:
        true if it successfully completed the query, false otherwise.
      • setValue

        public void setValue​(String fieldName,
                             @Nullable
                             Object value)
        Updates the field given by fieldName in all objects inside the query result.

        This method will automatically try to convert numbers and booleans that are given as String to their appropriate type. For example "10" will be converted to 10 if the field type is RealmFieldType.INTEGER.

        Using the typed setters like setInt(String, int) will be faster than using this method.

        Parameters:
        fieldName - field to update
        value - value to update with.
        Throws:
        IllegalArgumentException - if the field could not be found, could not be updated or the argument didn't match the field type or could not be converted to match the underlying field type.
      • setNull

        public void setNull​(String fieldName)
        Sets the value to null for the given field in all of the objects in the collection.
        Parameters:
        fieldName - name of the field to update.
        Throws:
        IllegalArgumentException - if field name doesn't exist or is a primary key property.
        IllegalStateException - if the field cannot hold null values.
      • setBoolean

        public void setBoolean​(String fieldName,
                               boolean value)
        Sets the boolean value of the given field in all of the objects in the collection.
        Parameters:
        fieldName - name of the field to update.
        value - new value for the field.
        Throws:
        IllegalArgumentException - if field name doesn't exist, is a primary key property or isn't a boolean field.
      • setByte

        public void setByte​(String fieldName,
                            byte value)
        Sets the byte value of the given field in all of the objects in the collection.
        Parameters:
        fieldName - name of the field to update.
        value - new value for the field.
        Throws:
        IllegalArgumentException - if field name doesn't exist, is a primary key property or isn't a byte field.
      • setShort

        public void setShort​(String fieldName,
                             short value)
        Sets the short value of the given field in all of the objects in the collection.
        Parameters:
        fieldName - name of the field to update.
        value - new value for the field.
        Throws:
        IllegalArgumentException - if field name doesn't exist, is a primary key property or isn't a short field.
      • setInt

        public void setInt​(String fieldName,
                           int value)
        Sets the int value of the given field in all of the objects in the collection.
        Parameters:
        fieldName - name of the field to update.
        value - new value for the field.
        Throws:
        IllegalArgumentException - if field name doesn't exist, is a primary key property or isn't an integer field.
      • setLong

        public void setLong​(String fieldName,
                            long value)
        Sets the long value of the given field in all of the objects in the collection.
        Parameters:
        fieldName - name of the field to update.
        value - new value for the field.
        Throws:
        IllegalArgumentException - if field name doesn't exist, is a primary key property or isn't a long field.
      • setFloat

        public void setFloat​(String fieldName,
                             float value)
        Sets the float value of the given field in all of the objects in the collection.
        Parameters:
        fieldName - name of the field to update.
        value - new value for the field.
        Throws:
        IllegalArgumentException - if field name doesn't exist, is a primary key property or isn't a float field.
      • setDouble

        public void setDouble​(String fieldName,
                              double value)
        Sets the double value of the given field in all of the objects in the collection.
        Parameters:
        fieldName - name of the field to update.
        value - new value for the field.
        Throws:
        IllegalArgumentException - if field name doesn't exist, is a primary key property or isn't a double field.
      • setString

        public void setString​(String fieldName,
                              @Nullable
                              String value)
        Sets the String value of the given field in all of the objects in the collection.
        Parameters:
        fieldName - name of the field to update.
        value - new value for the field.
        Throws:
        IllegalArgumentException - if field name doesn't exist, is a primary key property or isn't a String field.
      • setBlob

        public void setBlob​(String fieldName,
                            @Nullable
                            byte[] value)
        Sets the binary value of the given field in all of the objects in the collection.
        Parameters:
        fieldName - name of the field to update.
        value - new value for the field.
        Throws:
        IllegalArgumentException - if field name doesn't exist, is a primary key property or isn't a binary field.
      • setDate

        public void setDate​(String fieldName,
                            @Nullable
                            Date value)
        Sets the Date value of the given field in all of the objects in the collection.
        Parameters:
        fieldName - name of the field to update.
        value - new value for the field.
        Throws:
        IllegalArgumentException - if field name doesn't exist, is a primary key property or isn't a Date field.
      • setObject

        public void setObject​(String fieldName,
                              @Nullable
                              RealmModel value)
        Sets a reference to another object on the given field in all of the objects in the collection.
        Parameters:
        fieldName - name of the field to update.
        value - new object referenced by this field.
        Throws:
        IllegalArgumentException - if field name doesn't exist, is a primary key property or isn't an Object reference field.
      • setDecimal128

        public void setDecimal128​(String fieldName,
                                  @Nullable
                                  Decimal128 value)
        Sets the Decimal128 value of the given field in all of the objects in the collection.
        Parameters:
        fieldName - name of the field to update.
        value - new value for the field.
        Throws:
        IllegalArgumentException - if field name doesn't exist, is a primary key property or isn't a Decimal128 field.
      • setObjectId

        public void setObjectId​(String fieldName,
                                @Nullable
                                ObjectId value)
        Sets the ObjectId value of the given field in all of the objects in the collection.
        Parameters:
        fieldName - name of the field to update.
        value - new value for the field.
        Throws:
        IllegalArgumentException - if field name doesn't exist, is a primary key property or isn't a ObjectId field.
      • setUUID

        public void setUUID​(String fieldName,
                            @Nullable
                            UUID value)
        Sets the UUID value of the given field in all of the objects in the collection.
        Parameters:
        fieldName - name of the field to update.
        value - new value for the field.
        Throws:
        IllegalArgumentException - if field name doesn't exist, is a primary key property or isn't a UUID field.
      • setList

        public <T> void setList​(String fieldName,
                                RealmList<T> list)
        Replaces the RealmList at the given field on all objects in this collection.
        Parameters:
        fieldName - name of the field to update.
        list - new value for the field.
        Throws:
        IllegalArgumentException - if field name doesn't exist, isn't a RealmList field , if the objects in the list are not managed or the type of the objects in the list are wrong.
      • isFrozen

        public boolean isFrozen()
      • addChangeListener

        public void addChangeListener​(RealmChangeListener<RealmResults<E>> listener)
        Adds a change listener to this RealmResults.

        Registering a change listener will not prevent the underlying RealmResults from being garbage collected. If the RealmResults 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 RealmResults<Person> results; // Strong reference to keep listeners alive
        
             \@Override
             protected void onCreate(Bundle savedInstanceState) {
               super.onCreate(savedInstanceState);
               results = realm.where(Person.class).findAllAsync();
               results.addChangeListener(new RealmChangeListener<RealmResults<Person>>() {
                   \@Override
                   public void onChange(RealmResults<Person> persons) {
                       // React to change
                   }
               });
             }
         }
         
         
        Parameters:
        listener - the change listener to be notified.
        Throws:
        IllegalArgumentException - if the change listener is null.
        IllegalStateException - if you try to add a listener from a non-Looper or IntentService thread.
      • addChangeListener

        public void addChangeListener​(OrderedRealmCollectionChangeListener<RealmResults<E>> listener)
        Adds a change listener to this RealmResults.

        Registering a change listener will not prevent the underlying RealmResults from being garbage collected. If the RealmResults 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 RealmResults<Person> results; // Strong reference to keep listeners alive
        
             \@Override
             protected void onCreate(Bundle savedInstanceState) {
               super.onCreate(savedInstanceState);
               results = realm.where(Person.class).findAllAsync();
               results.addChangeListener(new OrderedRealmCollectionChangeListener<RealmResults<Person>>() {
                   \@Override
                   public void onChange(RealmResults<Person> persons, OrderedCollectionChangeSet changeSet) {
                       // React to change
                   }
               });
             }
         }
         
         
        Parameters:
        listener - the change listener to be notified.
        Throws:
        IllegalArgumentException - if the change listener is null.
        IllegalStateException - if you try to add a listener from a non-Looper or IntentService thread.
      • removeAllChangeListeners

        public void removeAllChangeListeners()
        Removes all user-defined change listeners.
        Throws:
        IllegalStateException - if you try to remove listeners from a non-Looper Thread.
        See Also:
        RealmChangeListener
      • asFlowable

        public Flowable<RealmResults<E>> asFlowable()
        Returns an Rx Flowable that monitors changes to this RealmResults. It will emit the current RealmResults when subscribed to. RealmResults will continually be emitted as the RealmResults are updated - onComplete will never be called.

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

        realm.where(Foo.class).findAllAsync().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:

         
         realm.where(Foo.class).findAllAsync().asFlowable()
              .filter(results -> results.isLoaded())
              .first()
              .subscribe( ... ) // You only get the results once
         
         

        Returns:
        RxJava Observable that only calls onNext. It will never call onComplete or OnError.
        Throws:
        UnsupportedOperationException - if the required RxJava framework is not on the classpath or the corresponding Realm instance doesn't support RxJava.
        IllegalStateException - if the Realm wasn't opened on a Looper thread.
        See Also:
        RxJava and Realm
      • asChangesetObservable

        public Observable<CollectionChange<RealmResults<E>>> asChangesetObservable()
        Returns an Rx Observable that monitors changes to this RealmResults. It will emit the current RealmResults when subscribed. For each update to the RealmResult a pair consisting of the RealmResults and the OrderedCollectionChangeSet will be sent. The changeset will be null the first time an RealmResults is emitted.

        RealmResults will continually be emitted as the RealmResults are updated - onComplete will never be called.

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

        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:

        realm.where(Foo.class).findAllAsync().asChangesetObservable() .observeOn(Schedulers.computation()) .map((rxResults, changes) -> doExpensiveWork(rxResults, changes)) .observeOn(AndroidSchedulers.mainThread()) .subscribe( ... );

        Returns:
        RxJava Observable that only calls onNext. It will never call onComplete or OnError.
        Throws:
        UnsupportedOperationException - if the required RxJava framework is not on the classpath or the corresponding Realm instance doesn't support RxJava.
        IllegalStateException - if the Realm wasn't opened on a Looper thread.
        See Also:
        RxJava and Realm
      • asJSON

        public String asJSON()
        Returns a JSON representation of the matches of a RealmQuery. Cycles will be returned as row indices. This is a helper method used to inspect data, or for debugging purpose, this method could pull a large string which could cause an OutOfMemory error.
        Returns:
        string representation of a JSON array containing entries of the resulting RealmQuery.
      • isValid

        public boolean isValid()
        Checks if the collection is still valid to use, i.e., the Realm instance hasn't been closed. It will always return true for an unmanaged collection.
        Specified by:
        isValid in interface io.realm.internal.ManageableObject
        Specified by:
        isValid in interface RealmCollection<E>
        Returns:
        true if it is still valid to use or an unmanaged collection, false otherwise.
      • get

        @Nullable
        public E get​(int location)
        Returns the element at the specified location in this list.
        Specified by:
        get in interface List<E>
        Specified by:
        get in class AbstractList<E>
        Parameters:
        location - the index of the element to return.
        Returns:
        the element at the specified index.
        Throws:
        IndexOutOfBoundsException - if location < 0 || location >= size().
      • first

        @Nullable
        public E first​(@Nullable
                       E defaultValue)
        Gets the first object from the collection. If the collection is empty, the provided default will be used instead.
        Specified by:
        first in interface OrderedRealmCollection<E>
        Returns:
        the first object or the provided default.
      • last

        @Nullable
        public E last​(@Nullable
                      E defaultValue)
        Gets the last object from the collection. If the collection is empty, the provided default will be used instead.
        Specified by:
        last in interface OrderedRealmCollection<E>
        Returns:
        the last object or the provided default.
      • deleteFromRealm

        public void deleteFromRealm​(int location)
        Deletes the object at the given index from the Realm. This also removes it from the collection.
        Specified by:
        deleteFromRealm in interface OrderedRealmCollection<E>
        Parameters:
        location - the array index identifying the object to be removed.
      • deleteAllFromRealm

        public boolean deleteAllFromRealm()
        This deletes all objects in the collection from the underlying Realm as well as from the collection.
        Specified by:
        deleteAllFromRealm in interface RealmCollection<E>
        Returns:
        true if objects was deleted, false otherwise.
      • sort

        public RealmResults<E> sort​(String fieldName)
        Sorts a collection based on the provided field in ascending order.
        Specified by:
        sort in interface OrderedRealmCollection<E>
        Parameters:
        fieldName - the field name to sort by. Only fields of type boolean, short, int, long, float, double, Date, and String are supported.
        Returns:
        a new sorted RealmResults will be created and returned. The original collection stays unchanged.
      • sort

        public RealmResults<E> sort​(String fieldName,
                                    Sort sortOrder)
        Sorts a collection based on the provided field and sort order.
        Specified by:
        sort in interface OrderedRealmCollection<E>
        Parameters:
        fieldName - the field name to sort by. Only fields of type boolean, short, int, long, float, double, Date, and String are supported.
        sortOrder - the direction to sort by.
        Returns:
        a new sorted RealmResults will be created and returned. The original collection stays unchanged.
      • sort

        public RealmResults<E> sort​(String[] fieldNames,
                                    Sort[] sortOrders)
        Sorts a collection based on the provided fields and sort orders.
        Specified by:
        sort in interface OrderedRealmCollection<E>
        Parameters:
        fieldNames - an array of field names to sort by. Only fields of type boolean, short, int, long, float, double, Date, and String are supported.
        sortOrders - the directions to sort by.
        Returns:
        a new sorted RealmResults will be created and returned. The original collection stays unchanged.
      • size

        public int size()
        Returns the number of elements in this query result.
        Specified by:
        size in interface Collection<E>
        Specified by:
        size in interface List<E>
        Specified by:
        size in class AbstractCollection<E>
        Returns:
        the number of elements in this query result.
      • min

        public Number min​(String fieldName)
        Finds the minimum value of a field.
        Specified by:
        min in interface RealmCollection<E>
        Parameters:
        fieldName - the field to look for a minimum on. Only number fields are supported.
        Returns:
        if no objects exist or they all have null as the value for the given field, null will be returned. Otherwise the minimum value is returned. When determining the minimum value, objects with null values are ignored.
      • minDate

        public Date minDate​(String fieldName)
        Finds the minimum date.
        Specified by:
        minDate in interface RealmCollection<E>
        Parameters:
        fieldName - the field to look for the minimum date. If fieldName is not of Date type, an exception is thrown.
        Returns:
        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.
      • max

        public Number max​(String fieldName)
        Finds the maximum value of a field.
        Specified by:
        max in interface RealmCollection<E>
        Parameters:
        fieldName - the field to look for a maximum on. Only number fields are supported.
        Returns:
        if no objects exist or they all have null as the value for the given field, null will be returned. Otherwise the maximum value is returned. When determining the maximum value, objects with null values are ignored.
      • maxDate

        @Nullable
        public Date maxDate​(String fieldName)
        Finds the maximum date.
        Specified by:
        maxDate in interface RealmCollection<E>
        Parameters:
        fieldName - the field to look for the maximum date. If fieldName is not of Date type, an exception is thrown.
        Returns:
        if no objects exist or they all have null as the value for the given date field, null will be returned. Otherwise the maximum date is returned. When determining the maximum date, objects with null values are ignored.
        Throws:
        IllegalArgumentException - if fieldName is not a Date field.
      • sum

        public Number sum​(String fieldName)
        Calculates the sum of a given field.
        Specified by:
        sum in interface RealmCollection<E>
        Parameters:
        fieldName - the field to sum. Only number fields are supported.
        Returns:
        the sum. If no objects exist or they all have null as the value for the given field, 0 will be returned. When computing the sum, objects with null values are ignored.
      • average

        public double average​(String fieldName)
        Returns the average of a given field.
        Specified by:
        average in interface RealmCollection<E>
        Parameters:
        fieldName - the field to calculate average on. Only number fields are supported.
        Returns:
        the average for the given field amongst objects in query results. This will be of type double for all types of number fields. If no objects exist or they all have null as the value for the given field, 0 will be returned. When computing the average, objects with null values are ignored.
      • deleteLastFromRealm

        public boolean deleteLastFromRealm()
        Removes the last object in the list. This also deletes the object from the underlying Realm.
        Specified by:
        deleteLastFromRealm in interface OrderedRealmCollection<E>
        Returns:
        true if an object was deleted, false otherwise.
        Throws:
        IllegalStateException - if the corresponding Realm is closed or in an incorrect thread.
      • deleteFirstFromRealm

        public boolean deleteFirstFromRealm()
        Removes the first object in the list. This also deletes the object from the underlying Realm.
        Specified by:
        deleteFirstFromRealm in interface OrderedRealmCollection<E>
        Returns:
        true if an object was deleted, false otherwise.
        Throws:
        IllegalStateException - if the corresponding Realm is closed or in an incorrect thread.
      • getRealm

        public Realm getRealm()
        Returns the Realm instance to which this collection belongs.

        Calling Closeable.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 query result.

        Returns:
        Realm instance this collection belongs to.
        Throws:
        IllegalStateException - if the Realm is an instance of DynamicRealm or the Realm was already closed.