Android Realm Handling Primary Key in Relational Object

旧巷老猫 提交于 2019-12-08 09:57:35

Proper way to create a new RealmObject with existing primary key is usage realm.createObject(EmailRealmModel.class, emailID)method.

Full code fragment:

realm.beginTransaction();
EmailRealmModel email = realm.createObject(EmailRealmModel.class, emailID);
mailBoxRealmModel.getEmails().add(email);
realm.commitTransaction();

Or, if you wish update stored in realm object using one of inmemory instances, you should call realm.copyToRealmOrUpdate(obj).

Example from documentation:

// For create managed proxy, you should wrap EmailRealmModel object by call copyToRealmXXX
EmailRealmModel email = realm.copyToRealmOrUpdate(new EmailRealmModel(id));
mailBoxRealmModel.getEmails().add(email);

On an unmanaged RealmObject, the RealmList fields must be initialized manually.

EmailRealmModel email = new EmailRealmModel();
email.setMessageId(emailID);

mailBoxRealmModel.setEmails(new RealmList<MailBoxRealmModel>());
mailBoxRealmModel.getEmails().add(email);
realm.insertOrUpdate(mailBoxRealmModel);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!