IndexOutOfBoundsException in ArrayAdapter

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) 
+4
source share
1 answer

Ok, I debugged it if someone had the same error, here is the solution:

If you use ListView.addHeader , the position onItemClick argument is shifted to 1. It seems that the position has nothing to do with the position in the adapter array. This CONSISTENT question contains the same conclusion that you should pay attention to what you add as headings.

My question above was actually not very useful, because the whole part of addHeader missing, it was impossible to answer the question by others, sorry. However, this answer may be useful to others.

+5
source

Source: https://habr.com/ru/post/1400440/


All Articles