Java – Update Realm tables only when Record is new (Java)

Update Realm tables only when Record is new (Java)… here is a solution to the problem.

Update Realm tables only when Record is new (Java)

I try to update my table only if the record is new (by checking that the record’s objectId does not already exist in my storage table), and my objectId is the primary key. I tried adding the condition realm.where(NotesRealmClass.class).notEqualTo("objectId", Id);
But it doesn’t seem to work, how can I only add a record when it’s new, or we can say – stop updating 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();

}

Solution

There are 2 options.

You can combine the method copyToRealm() with try... catch together. Realm does not allow you to create an object with the same primary key and throw an 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();
    }
}

In order to do not try... Do the same thing in catch cases and get closer to your approach, which you should 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();

}

Related Problems and Solutions