2013-01-21 91 views
1

我有問題從列表視圖(和數據庫)刪除項目。到目前爲止,我已經遵循這個例子: http://www.vogella.com/articles/AndroidSQLite/article.html但我不喜歡刪除那裏(總是刪除第一個按鈕)。Android的sqlite從列表視圖刪除

這裏是我的活動類:

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?

回答

2

您可以通過

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; 
      } 
     });  

讓您的shoping的數據的ID爲刪除項目

adapetr.remove(list.get(i)); 然後在列表視圖上調用notifydatasetchanged

+0

謝謝,這工作。如果你有時間的話,我還有兩個小問題。 1)爲什麼eclipse會說這個列表必須是最終的?我不認爲列表可以是最終的,它必須能夠改變? 2)如何刪除後「刷新」列表?我試過「adapter.notifyDataSetChanged()」,但似乎沒有工作 - 也許是因爲它也希望我把適配器作爲最終的,它不會再改變它? – user1985273

1

你可以得到從ListView中選擇的項目,然後從列表檢查自己的ID如下,

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