2016-12-31 86 views
2
@Override 
public boolean onItemMove(int fromPosition, int toPosition) { 

    RealmList<Note> results = new RealmList<>(); 
    results.addAll(mNotes.subList(0, mNotes.size())); 

    if (fromPosition < toPosition) { 
     for (int i = fromPosition; i < toPosition; i++) { 
      Collections.swap(results, i, i + 1); 
     } 
    } else { 
     for (int i = fromPosition; i > toPosition; i--) { 
      Collections.swap(results, i, i - 1); 
     } 
    } 

    mNotes = results.where().findAll(); 
    notifyItemMoved(fromPosition, toPosition); 
    return true; 
} 

我想執行交換功能重新排列adapter.Basically我與名單上的項目和拖處理項目的順序和刪除我要重新排列順序。我所做的是將RealmResults mNotes中的值複製到RealmList結果並完成了swap。如何將其返回到Realm數據庫?如何執行上RealmResults交換功能

mNotes = results.where()。findAll(); 這行代碼是不可能的,因爲RealmList不處於受管模式。

+0

我當然希望你有一個對應於該項目的位置的字段。 – EpicPandaForce

+0

@sreejith'RealmResults'元素不能直接交換。正如@EpicPandaForce所建議的,我認爲你需要額外的領域(讓我們稱之爲「職位」)。您可以使用該字段對RealmResults進行排序,然後交換對象,然後交換位置字段的值。 – geisshirt

+0

感謝都爲您的建議我嘗試排序這樣mNotes.sort(新比較(){ @覆蓋 公衆詮釋方法比較comments.Based(注O1,O2注){ 回報results.indexOf(O1。 getId()) - results.indexOf(o2.getId()); } });但這隻適用於api 24。使用android.And和Collection.sort方法不能爲realmResults執行此操作! –

回答

0

我相信你需要使用

copyToRealmOrUpdate方法來複制你的非託管集合:

// Initialize Realm 
Realm.init(context); 
// Get a Realm instance for this thread 
Realm realm = Realm.getDefaultInstance(); 
realm.copyToRealmOrUpdate(results); 
+0

不適合我! 。我正在使用RealmResults mNotes = realm.where(Note.class).findAll();爲RecyclerViewAdapter。由於交換不能直接完成RealmResults,我將其轉換爲RealmList並執行swap.After交換後,我需要將它放回RealmResults(在我的情況下爲mNotes)。 - –