我有两个对象:MailBox
和Email
。每个接收器都有许多Emails
。
public class MailBoxRealmModel extends RealmObject {
@PrimaryKey
private long id;
private String name;
private String mailboxId;
private RealmList<EmailRealmModel> emails;
}
public class EmailRealmModel extends RealmObject {
@PrimaryKey
private long EmailId;
private String Name;
private String Text;
private String Tag;
private int Type;
private String Time;
private int Status;
}
如何在向MailBoxRealmModel添加电子邮件时使用**realm.insertOrUpdate**
?
EmailRealmModel email = new EmailRealmModel();
email.setMessageId(emailID);
realm.insertOrUpdate(email );
mailBoxRealmModel.getEmails().add(email);
我在这一行得到一个空指针异常email
:
mailBoxRealmModel.getEmails().add(email);
例外:
引起:java.lang.NullPointerException:尝试在空对象引用上调用虚方法'boolean io.realm.RealmList.add(io.realm.RealmModel)' 在com.koa.mailbox.MailBoxActivity $ 1.execute(MailBoxActivity.java:123) 在io.realm.Realm.executeTransaction(Realm.java:1253) 在com.koa.mailbox.MailBoxActivity.test(MailBoxActivity.java:88) 在com.koa.mailbox.MailBoxActivity.onCreate(MailBoxActivity.java:71) 在android.app.Activity.performCreate(Activity.java:6876) 在android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1135) 在android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3207) 在android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3350) 在android.app.ActivityThread.access $ 1100(ActivityThread.java:222) 在android.app.ActivityThread $ H.handleMessage(ActivityThread.java:1795) 在android.os.Handler.dispatchMessage(Handler.java:102) 在android.os.Looper.loop(Looper.java:158) 在android.app.ActivityThread.main(ActivityThread.java:7229) at java.lang.reflect.Method.invoke(Native Method)
答案 0 :(得分:1)
使用现有主键创建新RealmObject的正确方法是使用realm.createObject(EmailRealmModel.class, emailID)
方法。
完整代码片段:
realm.beginTransaction();
EmailRealmModel email = realm.createObject(EmailRealmModel.class, emailID);
mailBoxRealmModel.getEmails().add(email);
realm.commitTransaction();
或者,如果您希望使用其中一个内存实例存储在realm对象中的更新,则应调用realm.copyToRealmOrUpdate(obj)
。
来自documentation的示例:
// For create managed proxy, you should wrap EmailRealmModel object by call copyToRealmXXX
EmailRealmModel email = realm.copyToRealmOrUpdate(new EmailRealmModel(id));
mailBoxRealmModel.getEmails().add(email);
答案 1 :(得分:0)
在非托管的RealmObject上,必须手动初始化RealmList
字段。
EmailRealmModel email = new EmailRealmModel();
email.setMessageId(emailID);
mailBoxRealmModel.setEmails(new RealmList<MailBoxRealmModel>());
mailBoxRealmModel.getEmails().add(email);
realm.insertOrUpdate(mailBoxRealmModel);