我的sqlite删除代码
public void deleteItem(int position) {
SQLiteDatabase db = getWritableDatabase();
db.delete(TABLE_PLACE, ID + "=?" + position , null);
}
再循环视图
@Override
public void onItemRemoved(int position) {
places.remove(position);
notifyItemRemoved(position);
notifyDataSetChanged();
}
我如何从SQLite
数据库中删除任何行,然后再从RecyclerView
中删除它呢?
我也遇到了类似的问题。将位置传递给SQLite DELETE语句的问题是,当数据库ID保持不变时,项的位置索引总是会更改。
与其依赖行ID(假设这是您的自动递增主键)来匹配您传递的位置,不如在表中创建另一列;让我们称之为itemindex。每次在数据库中创建新行时,您都应该首先将item_index值(整数)设置为ArrayList的大小(就像您用来膨胀回收视图的值一样),这将使第一行的item_index=0,第二行=1,第三行=2,依此类推
//EXAMPLE:
YourDataBaseHelper yourDataBaseHelper = new YourDataBaseHelper(/*proper parameters*/);//your database Class object
YourData yourData = new YourData(); //your setters and getters Class object
ArrayList<YourData> yourDataCounter = yourDataBaseHelper.getItems();//yourDataBaseHelper.whatever method you use to populate your ArrayList
yourData.set_itemIndex(yourDataCounter.size());
yourDataBaseHelper.addRow(yourData);//whatever method you use to insert rows
现在,我们仍然存在item_index和传递的位置值不匹配的问题。您可以通过进入dataBaseHelper类来解决此问题,并且在deleteItem方法中,您可以执行以下操作:
public void deleteItem(int position){
SQLiteDatabase db = getWritableDatabase();
db.execSQL("DELETE FROM " + TABLE_PLACE + " WHERE " +
ITEM_INDEX + " = " + position + ";");
db.execSQL("UPDATE " + TABLE_PLACE + " SET " + ITEM_INDEX + " = " +
ITEM_INDEX + " -1 " + " WHERE " + ITEM_INDEX + " > " + position + ";");
db.close();
}
UPDATE语句很重要,因为它只需将item_index列中大于传递位置值的所有值减去1,就可以确保item_indexs值始终与recyclerview位置匹配。
所有这些都可以在适配器类中的一个名为itemRemoved的方法中启动,该方法可以由onClick方法调用:
private ArrayList<YourData> yourData = new ArrayList<>();
private Context context;
public YourAdapter(ArrayList<YourData> yourData, Context context) {
this.yourData = yourData;
this.context = context;
}
public void itemRemoved(int position) {
YourDataBaseHelper yourDataBaseHelper = new YourDataBaseHelper(/*proper parameters*/);
yourData.remove(position);
notifyItemRemoved(position);
yourDataBaseHelper.deleteItem(position);
}
我希望这能有所帮助。
你能试试这种方法吗:
public void deleteItem(int position) {
SQLiteDatabase db = getWritableDatabase();
db.delete(TABLE_PLACE, ID + "=?" + position , null);
//you can try theese following 2 lines to delete
db.execSQL("DELETE FROM " + TABLE_NAME+ " WHERE "+COlUMN_NAME+"='"+value+"'");
db.close();
places.remove(position);
adapter.notifyDataSetChanged();
//or like this
adapter.notifyItemRemoved(position);
}