2016-11-29 111 views
0

我有这个类如何在关系中删除领域?

class Student extends RealmObject { 
    public String code; 
    public String name; 
    public String email; 
    public Course course; 
} 

class Course extends RealmObject { 
    public String code; 
    public String name; 
} 

class Sync { 
    // ... 
    // To sync data I am using retrofit, look the method to update course 
    public void onResponse(Call<...> call, Response<...> response) { 
     if (response.isSuccessful()) { 
      realm.executeTransactionAsync(new Realm.Transaction() { 
       @Override 
       public void execute(Realm realm) { 
        realm.delete(Course.class); 
        realm.copyToRealm(response.body()); 
       } 
      }); 
     } 
    } 
} 

后调用同步更新课程,所有学生对象都有其课程设置为null,这叫做境界后,预期的行为删除? 即使再次填充表后,Student上的课程仍为空。

今天我做的代码这一变化:

class Course extends RealmObject { 
    @PrimaryKey 
    public String code; 
    public String name; 
} 

class Sync { 
    // ... 
    // To sync data I am using retrofit, look the method to update course 
    public void onResponse(Call<...> call, Response<...> response) { 
     if (response.isSuccessful()) { 
      realm.executeTransactionAsync(new Realm.Transaction() { 
       @Override 
       public void execute(Realm realm) { 
        realm.copyToRealmOrUpdate(response.body()); 
       } 
      }); 
     } 
    } 
} 

我做了这个为时已晚,以避免删除课程。

我能做些什么来恢复参考课程并将其重新设置为学生?

谢谢。

回答

1

这是预期的行为,因为您通过删除指向的对象来使对象链接无效。

要恢复它们,您必须重新设置链接。


另一种解决方案是不删除您仍然需要的课程。如果您使用@PrimaryKey注释code,这样做会这样做,这样您就可以“更新”已经在其中的课程。然后问题就是不再在回复中删除课程/学生,但there are solutions ready-made for that

public class Robject extends RealmObject { 
    @PrimaryKey 
    private String code; 

    @Index 
    private String name; 

    //... 

    @Index 
    private boolean isBeingSaved; 

    //getters, setters 
} 

而且

// background thread 
Realm realm = null; 
try { 
    realm = Realm.getDefaultInstance(); 
    realm.executeTransaction(new Realm.Transaction() { 
     @Override 
     public void execute(Realm realm) { 
      Robject robject = new Robject(); 
      for(Some some : somethings) { 
       robject.set(some....); 
       realm.insertOrUpdate(robject); 
      } 
      realm.where(Robject.class) 
       .equalTo(Robject.IS_BEING_SAVED, false) // compile 'dk.ilios:realmfieldnameshelper:1.1.0' 
       .findAll() 
       .deleteAllFromRealm(); // delete all non-saved data 
      for(Robject robject : realm.where(Robject.class).findAll()) { // realm 0.89.0+ 
       robject.setIsBeingSaved(false); // reset all save state 
      } 
     } 
    }); 
} finally { 
    if(realm != null) { 
     realm.close(); 
    } 
} 
+0

谢谢。我认为即使在删除课程之后,Realm也会在学生中保留某种身份证件。表格再次填充后,可以恢复引用。我遵循你的提示使用注解'@ PrimaryKey',现在我正在避免从领域删除对象。我会解决这个问题。 – diegofesanto