I would like to implement a click listener for the CheckBoxes of a ListView that uses a custom adapter. Like this:

I know about the existence of the choiceMode, but I would like to implement myself.
I’m trying to apply good practices.
This is how my adapter looks like:
public class TaskListAdapter extends ArrayAdapter<ListTask> {
private ArrayList<ListTask> mItems;
private ArrayList<Boolean> mChecked;
private LayoutInflater mInflater;
public TaskListAdapter(Context context, int textViewResourceId, ArrayList<ListTask> items) {
super(context, textViewResourceId, items);
this.mItems = items;
// Cache the LayoutInflate to avoid asking for a new one each time
mInflater = LayoutInflater.from(context);
// Initialize all checkboxes with false value
mChecked = new ArrayList<Boolean>();
for (int i = 0; i < this.getCount(); i++) {
mChecked.add(i, false);
}
}
@Override
public View getView(final int position, View convertView, ViewGroup parent) {
final ViewHolder holder;
if (convertView == null) {
convertView = mInflater.inflate(R.layout.list_row, null);
holder = new ViewHolder();
holder.checkbox = (CheckBox) convertView.findViewById(R.id.mycheckbox);
holder.text = (TextView) convertView.findViewById(R.id.mytext);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
MyList mylist = mItems.get(position);
holder.text.setText(mylist.getMyText());
// Create a listener for the CheckBox
holder.checkbox.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
if (holder.checkbox.isChecked()) {
mChecked.set(position, true);
} else {
mChecked.set(position, false);
}
}
});
holder.checkbox.setChecked(mChecked.get(position));
return convertView;
}
static class ViewHolder {
CheckBox checkbox;
TextView text;
}
}
When I run my app, I get this error:
java.lang.IndexOutOfBoundsException:
Invalid location 0, size is 0
That errors is thrown by the line
holder.checkbox.setChecked(mChecked.get(position));
that is just before the return statement.
If I comment it and re-run the app, it shows the list, but when I click on a checkbox it throws also a IndexOutOfBoundsException for this line:
mChecked.set(position, true);
that is inside the “if” statement that checks if the checkbox is checked.
What am I doing wrong?
Did you check the value of position? Also did you ensure that your targeting the right views and even populating your list? Chances are you didn’t populate your ListView. From what I remember position was NOT the variable I was interested in when it came to the ListView and CheckBoxes.