Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/279.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
仅当记录为新记录时更新领域表(Java)_Java_Android_Realm - Fatal编程技术网

仅当记录为新记录时更新领域表(Java)

仅当记录为新记录时更新领域表(Java),java,android,realm,Java,Android,Realm,仅当记录是新记录时(通过检查记录的objectId,我存储的表中还不存在记录),我才尝试更新我的表。我的objectId是主键。我试图添加条件realm.where(NotesRealmClass.class).notEqualTo(“objectId”,Id) 但它似乎不起作用。只有当记录是新的,或者我们可以说-停止更新以前存储的记录时,我如何才能添加记录 public void storeNotes( String Id, String Title ,String Location) {

仅当记录是新记录时(通过检查记录的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();

}

检查该id的对象数是否等于0-如果为真,请插入新对象:

if (realm.where(NotesRealmClass.class).equalTo("objectId", Id).count() == 0) {
    realm.copyToRealm(Notes);
}
有两种选择

您可以将方法
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方法;异常速度很慢,如果您试图插入数千个对象,那么最终可能会非常昂贵。第二种方法是可行的——我们没有像Swift中那样的方法。Insert比copyToRealm更快。因此,请使用insert而不是copyToRealm
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();

}