Realm relation field always null [duplicate]

2019-09-11 08:12发布

This question already has an answer here:

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?

2条回答
乱世女痞
2楼-- · 2019-09-11 08:46

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.

查看更多
Ridiculous、
3楼-- · 2019-09-11 09:06

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.

查看更多
登录 后发表回答