Ignacio Hernandez Ignacio Hernandez - 1 month ago 9
Android Question

Java android Index out of Bound exception on Click event

I am having an issue with an Onclick event that keeps giving me an Out Of Bounds Exception . I basically have a list of car names about 30 of them on the list, when someone clicks a car name a checkmark appears next to it . When someone clicks it again I make the checkmark dissapear and that is usually when I get an out of bounds exceptions .. this is my code

private ArrayList<Integer> selected_positions= new ArrayList<>();
binding.list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> arg0, View view, int position, long id) {


if(selected_positions.contains(position)) {
// Position is already CheckMarked so remove
selected_positions.remove(position);
} else {
// Position Clicked for the 1st time
selected_positions.add(position);
}



final FilterCarsAdapter FS = new FilterCarsAdapter(getActivity(), binding,selected_positions);
binding.list.setAdapter(FS);


}
});


I am basically holding the values that are clicked inside the Selected_Positions ArrayList by Position . The issue is for instance clicks always work, if I click the item in index 2 then the checkmark appears but if I click it again to remove it I get java.lang.IndexOutOfBoundsException: Invalid index 2, size is 1 and if I position 5 then i get java.lang.IndexOutOfBoundsException: Invalid index 5, size is 1 . Any help would be great as I am new to Java .

Answer

The problem that when u use selected_positions.remove(position); it's trying to find and remove Integer at position position number.

you need: selected_positions.remove((Integer)position);