Search code examples
androidrealm

Load a single field of the object in realm


Suppose I have a Book object(id, name, author).

Suppose I have a big list of books, is it possible to retrieve only the names of these books without retrieving the entire objects?


Solution

  • Suppose I have a big list of books, is it possible to retrieve only the names of these books without retrieving the entire objects?

    Sure, see:

    private RealmChangeListener<RealmResults<Book>> listener = (results) -> {
        adapter.updateData(results);
    };
    
    RealmResults<Book> books;
    
    void blah() {
        books = realm.where(Book.class).findAllAsync();
        books.addChangeListener(listener);
    }
    

    And

    public class MyAdapter extends ___Adapter {
       ...
    
       public class ViewHolder /* ... */ {
           public void bind(Book book) {
               bookName.setText(book.getName());
           }
       }
    }
    

    The reason this would work is that while RealmResults evaluates "how to access the given objects", you actually load only the name of the book, by calling book.getName().

    Basically, managed RealmObjects are lazily accessed, and Realm itself only loads given object properties when that given property's accessor is called: in this case, book.getName().


    As for getting a List<String>, not really. That would read the property from every single object.