How to fix ArrayIndexOutOfBoundsException in your custom ListAdapter

If you are creating your own ListAdapter, perhaps you want to show different list items, or list item headings in your list by overriding the getItemViewType and the getViewTypeCount in the implemented Adapter class, then you may have come across the ArrayIndexOutOfBoundsException, as the example below:

ERROR/AndroidRuntime(400): FATAL EXCEPTION: main  
ERROR/AndroidRuntime(400): java.lang.ArrayIndexOutOfBoundsException  
ERROR/AndroidRuntime(400): at android.widget.AbsListView$RecycleBin.addScrapView(  
ERROR/AndroidRuntime(400): at android.widget.AbsListView.trackMotionScroll(  
ERROR/AndroidRuntime(400): at android.widget.AbsListView.onTouchEvent(  
ERROR/AndroidRuntime(400): at android.widget.ListView.onTouchEvent(  

The solution

The reason, is most likely because the getItemViewType method is returning the wrong values!

The different view types returned in getItemViewType, should be zero based, starting at 0, as shown in this example:

//inside your custom Adapter 
private static final int REGULAR = 0;  
private static final int HEADER = 1;

public int getItemViewType(int position) {  
    return positionShouldBeHeader(position) ? HEADER : REGULAR;
public int getViewTypeCount() {  
    return 2;

This example uses two different views, you could specify additional view types.

  • getViewTypeCount should return the correct number of different views you have
  • getItemViewType should return a view type, starting with 0.

The different numbers, starting at 0, are just to separate the different view types, you can, and should, create variables for them to make the code easier to understand.

comments powered by Disqus