我在从 ListView (和数据库)中删除项目时遇到问题。到目前为止,我已经按照这个例子: http://www.vogella.com/articles/AndroidSQLite/article.html但我不喜欢那里的删除(总是删除第一个的按钮)。
这是我的 Activity 课:
public class FirstActivity extends ListActivity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_1);
final ShoppingSQL shoppingSQL = new ShoppingSQL(this);
List<ShoppingData> list = shoppingSQL.getAll();
ArrayAdapter<ShoppingData> adapter = new ArrayAdapter<ShoppingData>(
this, android.R.layout.simple_list_item_1, list);
setListAdapter(adapter);
this.getListView().setLongClickable(true);
this.getListView().setOnItemLongClickListener(new OnItemLongClickListener() {
public boolean onItemLongClick(AdapterView<?> parent, View v, int position, long id) {
Log.w("DELETED", " DELETED");
shoppingSQL.delete((int)id);
return true;
}
});
}
protected void onListItemClick(ListView l, View v, int position, long id) {
super.onListItemClick(l, v, position, id);
Log.w("CLICKED", "CLICKED");
}
如您所见,我设置了长按的监听器以及需要 ID 的删除方法。问题与 ID 相关,我目前给它的似乎只是订单号 (0, 1, 2, 3) - 而不是数据库中的实际 ID。那么,我的问题是如何获得真实 ID?
最佳答案
您可以通过以下方式获取您的购物数据ID
this.getListView().setOnItemLongClickListener(new OnItemLongClickListener() {
public boolean onItemLongClick(AdapterView<?> parent, View v, int position, long id) {
Log.w("DELETED", " DELETED");
//here You can get your id by
list.get(position).getID();
//getID id the getter method of shoppingdata ,here you can declare your method for ID as whatever you have in shopping data
shoppingSQL.delete((int)list.get(position).getID());
return true;
}
});
用于删除项目
adapetr.remove(list.get(i)); 然后在 ListView 上调用 notifydatasetchanged
关于Android sqlite 从 ListView 中删除,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14433142/