My problem is, that in the ListView/Database only the topmost “comment” gets deleted, but I want, that the “comment” which are pressed get deleted.
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
datasource = new CommentsDataSource(this);
datasource.open();
List<Comment> values = datasource.getAllComments();
// Use the SimpleCursorAdapter to show the
// elements in a ListView
ArrayAdapter<Comment> adapter = new ArrayAdapter<Comment>(this,
android.R.layout.simple_list_item_1, values);
setListAdapter(adapter);
this.getListView().setClickable(true);
this.getListView().setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
Toast.makeText(MainActivity.this, "postion: " + getListView().getSelectedItemPosition(), Toast.LENGTH_SHORT).show();
Here is the problem, namely at getcount > 0.
ArrayAdapter<Comment> adapter = (ArrayAdapter<Comment>) getListAdapter();
Comment comment = null;
if (getListAdapter().getCount() > 0) {
comment = (Comment) getListAdapter().getItem(0);
datasource.deleteComment(comment);
adapter.remove(comment);
}
return;
}});
}
Using getItem(0) is always going to remove the first item in the adapter (and therefore the listview).
If you want to remove the items when they are clicked, in onItemClick, use the following code.
That’s all there is to it.