android sdk validation,android – Room Invalidation tracker初始化两次

本文探讨了在自定义项目布局的水平Recycler View中,如何避免拖动项目时数据库数据被意外删除的问题。作者分享了在onItemMove方法和数据库操作中遇到的错误,并提供了可能的解决方案,着重于处理'Item moved'错误和确保数据一致性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

我有一个水平回收站视图,其中包含自定义项目.每个项目都可以在Recycler视图中保存当前项目的位置.我想使用拖放移动项目时更新项目位置.但是当水平视图中有三个以上的项目时,数据会被删除.请帮帮我.

Source Code

这是我在Logcat中得到的:

E/ROOM: Invalidation tracker is initialized twice :/.

E/Item moved: 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,

0, fromContentValues, "posItem =" + fromPosition, null);

db.getOpenHelper().getWritableDatabase().update(nexName,

0, toContentValues, "posItem =" + toPosition, null);

db.setTransactionSuccessful(); //setting Transaction Successful

} finally {

db.endTransaction(); // commit or rollback

db.close(); //closing database

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值