user6668564
user6668564

Reputation:

How to implement drag and drop with ItemTouchHelper and cursors

I've been attempting to implement drag and drop features into my notes app using ItemTouchHelper however I am struggling to figure out how to get it to work with cursors. I am currently retrieving stored note data from the database using a cursor loader and a content provider, and the adapter receives it's data from the returned cursor as shown.

public void onBindViewHolder(RecyclerViewAdapter.MyViewHolder holder, int position) {
    mCursor.moveToPosition(position);
    String title = mCursor.getString(mCursor.getColumnIndex(NotesContract.COL_TITLE));
    String body = mCursor.getString(mCursor.getColumnIndex(NotesContract.COL_BODY));
    holder.titleText.setText(title);
    holder.bodyText.setText(body);
}

The problem I am having is that I don't know how I would keep track of the position of the moved items in the list when I drag and drop them. I can't change the order of the rows in the cursor. I have only seen examples where the data source for the adapter is a List. I have considered copying my cursor data into a list of Note objects, so that I could rearrange them to reflect the changes made by dragging and dropping, but this seems to defeat all you gain by using cursors and cursor loader. Also when cursor loader finishes loading it will return a new cursor with all the results in the original order again and populate the adapter accordingly, so any changes made to the order if my new List would be lost.

Does anyone know how to do this or am I going about this entirely the wrong way using cursors and a loader? Any help would be much appreciated. Thanks!

Upvotes: 4

Views: 910

Answers (2)

XxGoliathusxX
XxGoliathusxX

Reputation: 982

A good tutorial how to implement drag and drop and swipe to dismiss you can find here

What exactly do you need that cursor for? If you have any specific question just add a comment. I worked a lot with this features!

Upvotes: 0

Magnus G
Magnus G

Reputation: 111

I have done this by adding a column named sort_order in the table to keep track of the sort order. When you drag and drop you update the sort_order in the onMove method in ItemTouchHelper.SimpleCallback.

Upvotes: 2

Related Questions