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();
}
答案 0 :(得分:4)
有两种选择。
您可以将方法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();
}
}
如果没有try...catch
并且更接近您的方法,那么您应该在代码中修复
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();
}
答案 1 :(得分:2)
检查具有该id的对象的数量是否等于0 - 如果这是真的,则插入新对象:
if (realm.where(NotesRealmClass.class).equalTo("objectId", Id).count() == 0) {
realm.copyToRealm(Notes);
}