Reputation: 1967
Im having problems with deleting items from listview(and database). So far i have followed this example: http://www.vogella.com/articles/AndroidSQLite/article.html but i dont like the delete there (button that always delets first one).
Here is my activity class:
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");
}
}
As you can see i have the listner for long clicks set up and also the delete method that requires an ID. The probelm is with the ID, the one im giving it at the moment seems to be just the order number (0, 1, 2, 3) - not the actual id in db. So, my question is how do i get the real id?
Upvotes: 1
Views: 5360
Reputation: 1932
You Can get your Id of Shoping data by
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;
}
});
For delete items
adapetr.remove(list.get(i)); then call notifydatasetchanged on listview
Upvotes: 2
Reputation: 11141
You can get the item that is selected from the ListView and then check its ID from the List as follows,
String selectedItem =(String) (MyListView.getItemAtPosition(position));
int ItemID = list.indexOf(selectedItem);
shoppingSQL.delete(ItemID);
Upvotes: 1