2013-01-21 96 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);