Realm relation field always null [duplicate]

2019-09-11 08:07发布

问题:

This question already has an answer here:

  • Cannot retrieve field values from realm object, values are null in debugger 3 answers

There are my models:

public class RChat extends RealmObject {
    @PrimaryKey
    private String              Id;
    private RMyTest Test;

    public RChat() {}
}

and

public class RMyTest extends RealmObject {
    @PrimaryKey
    private String myName;

    public RMyTest() {
    }
}

And I'm using like this:

mRealm = Realm.getInstance(this);


        mRealm.beginTransaction();
        final RChat chat = mRealm.createObject(RChat.class);
        chat.setId("test");
        RMyTest rProfile = mRealm.createObject(RMyTest.class);
        rProfile.setMyName("alireza test");
        chat.setTest(rProfile);
        //mRealm.copyToRealmOrUpdate(chat);
        mRealm.commitTransaction();

        RChat chat1 = mRealm.where(RChat.class).equalTo("Id","test").findFirst();

but the chat1 object's Test field has null value always. How can I fix this problem?

回答1:

The code looks correct. If you get null by examine the chat1's Test field in the debug window, you will get a null value. That is expected.

Realm will generate a proxy class and override the getters/setters in the proxy class. So if you try

RMyTest rProfile = chat1.getTest();

I am sure you can get the corresponding RMyTest Object instead of null.

This behaviour is documented here.



回答2:

I was thinking my objects must not be null directly but the point is Realm uses proxy for models and the proxy is not null actually.