1

我在从列表视图(和数据库)中删除项目时遇到问题。到目前为止,我一直遵循这个例子: http ://www.vogella.com/articles/AndroidSQLite/article.html但我不喜欢那里的删除(总是删除第一个的按钮)。

这是我的活动课:

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)——而不是 db 中的实际 ID。所以,我的问题是我如何获得真实身份?

4

2 回答 2

2

您可以通过以下方式获取您的购物 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

于 2013-01-21T06:18:25.597 回答
1

您可以获取从 ListView 中选择的项目,然后从 List 中检查其 ID,如下所示,

    String selectedItem =(String) (MyListView.getItemAtPosition(position));
    int ItemID = list.indexOf(selectedItem);
    shoppingSQL.delete(ItemID);
于 2013-01-21T06:18:18.313 回答