我有一个水平回收站视图,其中包含自定义项目.每个项目都可以在Recycler视图中保存当前项目的位置.我想使用拖放移动项目时更新项目位置.但是当水平视图中有三个以上的项目时,数据会被删除.请帮帮我.
Source Code
Source Code
这是我在Logcat中得到的:
E/ROOM: Invalidation tracker is initialized twice :/.
E/Itemmoved: Counterfrom3
next item:to2
在onCreate中初始化数据库.
db = Room.databaseBuilder(getApplicationContext(),AppDatabase.class,DB_NAME) .fallbackToDestructiveMigration() .allowMainThreadQueries() .build();
RecyclerView适配器代码.
@Override public boolean onItemMove(int fromPosition,int toPosition) { String name = dataSet.get(fromPosition).getName(); //this will make "Add item" do not move from its first position.. if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) { if (!(Objects.equals(name,"Add") || (toPosition == 0 && fromPosition == 1))) { Collections.swap(dataSet,fromPosition,toPosition); MoveItem(fromPosition,toPosition); notifyItemMoved(fromPosition,toPosition); return true; } } return false; }
移动项目时更新数据的代码.
public static void MoveItem(int fromPosition,int toPosition){ String name = data.get(fromPosition).getName(); //This gets the current item name in the view String nexName = data.get(toPosition).getName(); //This gets the next item name in the view ContentValues fromContentValues = new ContentValues(); fromContentValues.put("posItem",toPosition); //adding data to ContentValues ContentValues toContentValues = new ContentValues(); toContentValues.put("posItem",fromPosition); Log.e("Item moved",name + "from" + fromPosition + "\n" + "next item:" + "to" + toPosition); db.beginTransaction(); try { db.getOpenHelper().getWritableDatabase().update(name,fromContentValues,"posItem =" + fromPosition,null); db.getOpenHelper().getWritableDatabase().update(nexName,toContentValues,"posItem =" + toPosition,null); db.setTransactionSuccessful(); //setting Transaction Successful } finally { db.endTransaction(); // commit or rollback db.close(); //closing database } }