I have trivial code involving ListView and ArrayAdapter that throws IndexOutOfBoundsException on some devices. The problem is that I do not know how this exception occurs, I only get the stack from the Android developer console.
The following is an example of the above code. How can an getItem ArrayAdapter operation fail for a position element? ArrayAdapter never changes, there is no other method in Activity .
I know what IndexOutOfBoundsException , I know that I can prevent it by checking the length first. But I'm curious: how does this exception occur here? How can someone click an event that does not exist in the data structure?
Short 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 } });
An 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)
source share