我有删除Row功能,如下:
public boolean removeData(int position) {
SQLiteDatabase db = this.getWritableDatabase();
db.delete(TABLE_NAME, COL_ID+"="+position, null);
return true;
}
此功能根据其唯一ID删除行。
如何更改此设置,以便在删除行后,该行下方的所有行都将向上移动以填充数据库中的空白区域?
答案 0 :(得分:1)
这违反了关系数据库的设计原则。行不以可预测的方式排序。因此,删除后您只能确定删除的记录似乎已经消失,但您无法控制任何记录的物理位置,包括哪些记录(如果有)现在覆盖已删除记录的空间。< / p>
查询数据是另一个主题。您可以指定排序顺序,可以使用query
方法作为参数。查询你的桌子时,结果将完全按照你的意愿出现:如果以前你的结果是亚当,夏娃,杰克,迈克尔,那么在删除杰克后,结果将是亚当,夏娃,迈克尔。
答案 1 :(得分:0)
显示的列表,该列表后面的域对象和数据库之间的相互作用是另一个主题。以下是我用于类似任务的一些代码片段。基本思路是,在读取将要显示的对象时,将数据库ID包含在对象中。因此,如果我阅读了产品列表,域类Product
将有一个id
字段,在读取时会使用数据库ID进行设置。
要使域对象显示在特定列表位置(例如用户点击删除按钮的位置),代码片段就是。
public void onClick(View view) {
Product product = (Product) ProductList.this.products.get(ProductAdapter.this.listView.getPositionForView((View) view.getParent()));
... now do whatever is necessary to delete the product, probably
calling a DAO class that deletes the object based on its id,
not the list position
ProductAdapter.this.notifyDataSetChanged();
}
答案 2 :(得分:0)
通过ListView中的TextView文本删除数据库中的行而不是通过TextView的位置删除来解决此问题。
现在看起来像这样:
//Erasebutton listener
final Button eraseButton = (Button) findViewById(R.id.eraseButton);
assert eraseButton != null;
eraseButton.setOnClickListener(new View.OnClickListener() { //erasebutton onclick
public void onClick(View eraseButton) {
SparseBooleanArray checked = questionList.getCheckedItemPositions();
for(int i = questionList.getCount() - 1; i >= 0; i--)
{
if(checked.get(i)) {
//What to do with selected listitems
TextView tv = (TextView) questionList.getChildAt(i).findViewById(R.id.checkedTextView1);
db.removeData(tv.getText().toString());
}
}
checked.clear();
Cursor newCursor = db.getData();
adapter.swapCursor(newCursor);
}
});
removeData 功能现在看起来像这样:
public boolean removeData(String question) {
SQLiteDatabase db = this.getWritableDatabase();
db.delete(TABLE_NAME, COL_QUESTION+"='"+question+"'", null);
return true;
}