I am trying to update my table only if a record is new (doesn't exists yet on my stored table by checking record's objectId ) my objectId is primary key. I tried to add condition realm.where(NotesRealmClass.class).notEqualTo("objectId", Id);
but it didn't seems to work how can i add a record only if record is new or we can say - stop updating the previously stored records
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();
}
There are 2 options.
You can use method copyToRealm()
with try...catch
. Realm doesn't allow to create object with the same primary key and throw the exception.
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();
}
}
For doing the same without try...catch
and more close to your approach you should make a fix in your code
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();
}
Check to see if the number of objects with that id is equal to 0 - if that's true, then insert your new object:
if (realm.where(NotesRealmClass.class).equalTo("objectId", Id).count() == 0) {
realm.copyToRealm(Notes);
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.