当前位置:首页 > 数据库 > SQlite

android – 在SQLite中保存重新排序的RecyclerView

所以我试图在我的待办事项列表应用程序中实现拖放,但是我在移动时保存行的顺序时遇到问题 – 即我移动了项目,退出应用程序并恢复到原始位置.我想到了一个解决方案.

我的解决方案

在我的表中创建一个列:specified_position.每次移动一行时,onItemMove()方法都会返回一个fromPosition和toPosition.将行的位置移动到toPosition,然后递增/更新那里及以上的所有值.每次读取表格时,它都会检查位置并根据它进行排序.

我的问题:

我的解决方案是否正确有没有更好,更容易的方法而不是这样做?非常感谢!

解决方法:

我的待办事项列表应用程序遇到了同样的问题.在这里,我与您分享我的解决方案.

首先,我在Database Helper上有一个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);
}

然后在活动或适配器上,你应该听你的位置更改项目,你需要有这样的功能.它将更新受此位置更改影响的所有项目的所有排序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
}

【说明】本文章由站长整理发布,文章内容不代表本站观点,如文中有侵权行为,请与本站客服联系(QQ:254677821)!