Android Realm - findAll returns objects with null parameters

Bugdr0id picture Bugdr0id · Aug 25, 2016 · Viewed 8.1k times · Source

I need to do a simple query in Realm, retrieve a list of MyModel object and later use it somewhere else in my app. It happens that once I query Realm, each object has null values, but the toString returns the expected values.

Model:

@RealmClass
public class MyModel extends RealmObject implements Serializable {

public static final String KEY_MODEL = "key_myModel";

@PrimaryKey
private int id;
private String myStr;
private int myInt;

//.... getters and setters

@Override
public String toString() {
    return "id = " + id
            + "\nmyStr = " + myStr
            + "\nmyInt = " + myInt;
}

}

How do I store the value:

public static void storeModel(MyModel model) {
        Realm realm = Realm.getDefaultInstance();
        realm.beginTransaction();
        realm.copyToRealm(model);
        realm.commitTransaction();
    }

How do I retrieve the objects:

public static RealmList<MyModel> getNewElementsFromIndex(int indexFrom) {
        Realm realm = Realm.getDefaultInstance();
        RealmResults<MyModel> allValues = realm.where(MyModel).greaterThan("id", indexFrom).findAll();

        RealmList<MyModel> finalList = new RealmList<MyModel>();
        finalList.addAll(allValues.subList(0, allValues.size()));
        return finalList;
    }

When i call getNewElementsFromIndex(value) i get a list of item, but all items in this list have the parameter myStr = null and myInt = 0.

What am I doing wrong?

Answer

EpicPandaForce picture EpicPandaForce · Aug 25, 2016

For managed realm objects, data is not copied to the fields, you obtain them through the proxy getter/setter calls.

Therefore, the fact that fields are null and toString() shows the values is completely expected and well-documented behavior.

To see the values, you have to add watches for the getter methods.

See the documentation.