I got a trivial code involving a ListView and a ArrayAdapter which throws a IndexOutOfBoundsException on some devices. The problem is: I do not know how this Exception occurs, I only get the stacktraces from the Developer Console of Android.
The reduced code example is shown below. How can the getItem operation of the ArrayAdapter fail for the position element? The ArrayAdapter is never changed, there is no other method in the Activity.
I know what a IndexOutOfBoundsException is, I know that I can prevent it by checking the length first. But I’m curious: How can this Exception happen here? How can someone click on a event which does not exist in the datastructure?
Reduced code:
public class EventListActivity extends Activity {
public void onStart() {
final ListView listview = new ListView(this);
final Event[] events = [Retrieve a Array from somewhere]
final ArrayAdapter<Event> a = new ArrayAdapter<Event>(this, R.layout.eventlistitem, events);
listview.setAdapter(a);
listview.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Event event = a.getItem(position);
^^^^^^^ throws Exception
}
});
Exception:
java.lang.IndexOutOfBoundsException
at java.util.Arrays$ArrayList.get(Arrays.java:75)
at android.widget.ArrayAdapter.getItem(ArrayAdapter.java:298)
at xxx.EventListActivity$3.onItemClick(EventListActivity.java:130)
Okay, I debugged it, in case someone has the same error, here is the solution:
If you use
ListView.addHeader, thepositionargument of theonItemClickis shifted by 1. Seems quite weird because the position then has nothing to do with the position in the array-adapter. This SO Question contains the same conclusion, you have to pay attention what you add as headers.My question above was in fact not very helpfull because the whole
addHeaderpart was missing, it was impossible to answer the question by others, sorry. Nevertheless, this answer might be helpfull for others.