簡體   English   中英

從listview中刪除Android sqlite

[英]Android sqlite delete from listview

我在從listview(和數據庫)中刪除項目時遇到問題。 到目前為止,我已經按照這個例子: 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。 所以,我的問題是如何獲得真正的身份?

您可以通過以下方式獲取您的購物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

您可以獲取從ListView中選擇的項目,然后從List中檢查其ID,如下所示,

    String selectedItem =(String) (MyListView.getItemAtPosition(position));
    int ItemID = list.indexOf(selectedItem);
    shoppingSQL.delete(ItemID);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM