嘿伙计们只是在记录是新的时才尝试更新我的表(通过检查记录的objectId我的存储表上还没有)我的objectId是主键,
我试图添加条件realm.where(NotesRealmClass.class).notEqualTo(“objectId”,Id);
但它似乎没有工作,我怎么能添加记录只有记录是新的或我们可以说 – 停止更新以前存储的记录
public void storeNotes( String Id, String Title ,String Location) {
realm.beginTransaction();
NotesRealmClass Notes = new NotesRealmClass();
Notes.setobjectId(Id);
Notes.setLocation(Location);
Notes.setTitle(Title);
realm.where(NotesRealmClass.class).notEqualTo("objectId", Id); // i tired to check if we already have the object with object Id
realm.copyToRealmOrUpdate(Notes);
Toast.makeText(context, "Notes Stored", Toast.LENGTH_SHORT).show();
realm.commitTransaction();
}
解决方法:
有2个选项.
您可以将方法copyToRealm()与try … catch一起使用. Realm不允许使用相同的主键创建对象并抛出异常.
public void storeNotes( String Id, String Title ,String Location) {
try {
realm.beginTransaction();
NotesRealmClass Notes = new NotesRealmClass();
Notes.setobjectId(Id);
Notes.setLocation(Location);
Notes.setTitle(Title);
realm.copyToRealm(Notes); // <======
Toast.makeText(context, "Notes Stored", Toast.LENGTH_SHORT).show();
realm.commitTransaction();
} catch (Exception error) {
realm.cancelTransaction();
}
}
为了做到这一点而不尝试…捕捉和更接近你的方法你应该在你的代码中修复
public void storeNotes( String Id, String Title ,String Location) {
realm.beginTransaction();
NotesRealmClass Notes = new NotesRealmClass();
Notes.setobjectId(Id);
Notes.setLocation(Location);
Notes.setTitle(Title);
if (realm.where(NotesRealmClass.class).equalTo("objectId", Id).count() == 0) {
// there are no object with this `Id`
realm.copyToRealmOrUpdate(Notes);
}
Toast.makeText(context, "Notes Stored", Toast.LENGTH_SHORT).show();
realm.commitTransaction();
}