Ignacio Hernandez Ignacio Hernandez - 1 year ago 65
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() {
public void onItemClick(AdapterView<?> arg0, View view, int position, long id) {

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

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


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 Source

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);

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download