2016-11-29 120 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