Need a little help


#1

Hello! I’m new to Realm. Found this pretty interesting, so I decided to toy around with it in a test project.

I’m having trouble understanding how I can convert results into an object in Java so I can use the properties (name, age, etc).

I know how to get a single result object, and use its properties:

 Realm realm = Realm.getDefaultInstance();

        realm.executeTransaction(new Realm.Transaction() {
            @Override
            public void execute(Realm realm) {
                Person person1 = realm.createObject(Person.class);
                person1.setId(1);
                person1.setName("James");
                person1.setAge(23);

                Person person2 = realm.createObject(Person.class);
                person2.setId(2);
                person2.setName("John");
                person2.setAge(30);
            }
        });

        Person person = realm.where(Person.class).equalTo("name", "John").findFirst();
        
        //Then, use the name:
        Log.d("Result", String.valueOf(person.getName()));

But, how would I return all results from the database, and access the fields such as age name, age…

RealmQuery<Person> query = realm.where(Person.class);
        RealmResults<Person> results = query.findAll();
        
        //^^^ How do I access the fields? Name field, age field, etc

Basically, I need to loop through the results and access the database name fields, age field etc. How do I do that?

I’m sorry if I’m not understanding how Realm works. Again, I’m new to this and trying to figure this out.

I appreciate any help! I’d really like to use this in my projects!


#2

There’s a code snippet that shows how to iterate over the results of a query in our java docs.

It’ll look like:

RealmResults<Person> guests = realm.where(Person.class).equalTo("invited", false).findAll();
realm.beginTransaction();
for (int i = 0; guests.size(); i++) {
    guests.get(i).setInvited(true);
}
realm.commitTransaction();

#3

Hi! Thanks for your reply.

I’m getting this error from guests.size();

Incompatible types.
Required:
boolean
Found:
int


#4

Opps! Never mind. Figure it out. Thanks for the help!