gpt4 book ai didi

Android Realm 处理关系对象中的主键

转载 作者:行者123 更新时间:2023-11-30 00:48:53 31 4
gpt4 key购买 nike

我有两个对象:MailBoxEmail。每个 Receiver 都有很多 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);

异常(exception):

Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'boolean io.realm.RealmList.add(io.realm.RealmModel)' on a null object reference at com.koa.mailbox.MailBoxActivity$1.execute(MailBoxActivity.java:123) at io.realm.Realm.executeTransaction(Realm.java:1253) at com.koa.mailbox.MailBoxActivity.test(MailBoxActivity.java:88) at com.koa.mailbox.MailBoxActivity.onCreate(MailBoxActivity.java:71) at android.app.Activity.performCreate(Activity.java:6876) at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1135) at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3207) at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3350)  at android.app.ActivityThread.access$1100(ActivityThread.java:222)  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1795)  at android.os.Handler.dispatchMessage(Handler.java:102)  at android.os.Looper.loop(Looper.java:158)  at android.app.ActivityThread.main(ActivityThread.java:7229)  at java.lang.reflect.Method.invoke(Native Method)

最佳答案

使用现有主键创建新 RealmObject 的正确方法是使用 realm.createObject(EmailRealmModel.class, emailID) 方法。

完整代码 fragment :

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

或者,如果您希望使用 inmemory 实例之一将更新存储在 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);

关于Android Realm 处理关系对象中的主键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41366560/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com