How to perform swap function on RealmResults

638 views Asked by At
@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;
}

I want to perform a swap function to re-arrange the order of items in the adapter.Basically I am dealing with a list on items and on drag and drop I want to rearrange the order.What I did is I copied values from RealmResults mNotes to RealmList results and done swap.How to put it back to the Realm database?

mNotes = results.where().findAll(); this line of code is not possible since the RealmList is not in managed mode.

1

There are 1 answers

1
Mina Wissa On

I believe you need to copy your un-managed collection using

copyToRealmOrUpdate method:

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