在 SQLite 中保存重新排序的 RecyclerView

Pla*_*iam 5 sqlite android android-recyclerview

所以我试图Drag-and-Drop在我的待办事项列表应用程序中实现,但是我在保存移动后的行顺序时遇到了麻烦 - 即我移动了项目,退出了应用程序,然后它恢复到原来的位置。我想到了一个解决办法。

我的解决方案:

在我的表中创建一列:specification_position。每次移动一行时,该onItemMove()方法都会返回 afromPositiontoPosition。将行的位置移动到toPosition,然后增加/更新那里和上面的所有值。每次读取表格时,它都会检查头寸并根据它对它们进行排序。

我的问题:

我的解决方案是否正确?有没有更好,更简单的方法来代替这样做?非常感谢!

小智 3

我的待办事项列表应用程序也遇到同样的问题。这里我把我的解决方案分享给大家。

首先,我的数据库助手有一个updateSortID()函数

public void updateSortID(Integer newID,int rowid)
{
     SQLiteDatabase db = this.getWritableDatabase();
        String strSQL = "UPDATE " +  TABLE_NAME_todos +  " SET " + ITEM_SORT_ID +  "=" + newID + " WHERE " + ID +" = "+ rowid;

        db.execSQL(strSQL);
}
Run Code Online (Sandbox Code Playgroud)

然后在活动或适配器上,您应该在其中监听项目的位置变化,您需要有这样的功能。它将更新受此位置更改影响的所有项目的所有排序 ID。

@Override
public void drop(int from, int to) {
    // TODO Auto-generated method stub

    Log.d("drop", String.valueOf(from));
    Log.d("drop", String.valueOf(to));

    ArrayList<Items> temp = db.getToDos();

    int tempstart = from;
    int tempend = to;

    if (from < to) {
        Log.d("up to down", "yes");
        db.updateSortID(temp.get(tempend).getSortID(), temp.get(tempstart).getID());
        for (int i = from; i <= to - 1; i++) {
            db.updateSortID(temp.get(i).getSortID(), temp.get(i+1).getID());
        }
    } else if (from > to) {
        Log.d("up to down", "no");
        db.updateSortID(temp.get(tempend).getSortID(), temp.get(tempstart).getID());            
        for (int i = from; i >= to + 1; i--) {
            db.updateSortID(temp.get(i).getSortID(), temp.get(i-1).getID());                
        }
    }

    listChanged(); // this is the method I call `notifyDataSetChanged()` method and other related functions
}
Run Code Online (Sandbox Code Playgroud)