问题
I'm trying to delete ListView items that are checked. It works if there is only one item checked but if there are two or three then the app force closes. On the error log it says:
E/AndroidRuntime(2173): java.lang.IndexOutOfBoundsException: Invalid location 2, size is 2
When having three items on the list and deleting 2. Can anyone help with correcting this error? Here is the code:
public void delete() {
btnDelete = (Button) findViewById(R.id.btnDelete);
btnDelete.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
for (int i = 0; i < list.getChildCount(); i++) {
View view = list.getChildAt(i);
CheckedTextView cv = (CheckedTextView) view.findViewById(R.id.checkList);
if(cv.isChecked()){
Log.i("DELETE", adapter.getItem(i).toString()+" "+cv.toString());
adapter.remove(adapter.getItem(i));
}
adapter.notifyDataSetChanged();
}
Toast.makeText(getApplicationContext(), "Selected Items Cleared", Toast.LENGTH_SHORT).show();
}
});
}
回答1:
The problem is with your for loop. you are iterating list view in the for loop by list.getChildCount() which is not correct read the Api doc correctly, replace it with adapter.getCount(); it will solve the problem.
来源:https://stackoverflow.com/questions/10418764/deleting-checked-listview-items