Java.lang.ArrayIndexOutOfBoundsException : length=27; index=-1 exception

Java.lang.ArrayIndexOutOfBoundsException : length=27; index=-1 exception … here is a solution to the problem.

Java.lang.ArrayIndexOutOfBoundsException : length=27; index=-1 exception

I’m getting this error when implementing a footer in the Recycle Bin View.

That’s what I did. I used two types to display different Views in a list, but something in the getItemCount() method was set incorrectly, or when I got the location of the clicked item model in the list.

This is what I have at the moment :

private final int VIEW_TYPE_ITEM = 0;
private final int VIEW_TYPE_FOOTER = 1;

@Override
public int getItemCount() {
    return mUsers == null ? 0 : mUsers.size() + 1;
}

@Override
public int getItemViewType(int position) {
    if (isFooterPosition(position)) {
        return VIEW_TYPE_FOOTER;
    }
    return VIEW_TYPE_ITEM;
}

private boolean isFooterPosition(int position) {
    return position == mUsers.size() + 1;
}

private User getUser (int position) {
    return mUsers.get(position - 1);  Here i'm getting an error mentioned in title
}

Edit:

if (holder instanceof UserHolder) {
        final User user = getUser(position);
        UserHolder userViewHolder = (UserHolder) holder;

userViewHolder.tvUserName.setText(user.getName());
        userViewHolder.mView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mOnItemClickListener.onItemClick(v, position);
            }
        });
    } else if (holder instanceof FooterViewHolder) {
        FooterViewHolder footerViewHolder = (FooterViewHolder) holder;
        Typeface typeface = Typeface.createFromAsset(mContext.getAssets(), "Lato-Thin.ttf");
        footerViewHolder.mButton.setTypeface(typeface);
    }

I have some items in the list for normal holder View and one for footer View.

Solution

mUsers.get(position - 1); Will crash when position is 0 because you are looking for invalid item at index -1.

If you were to add a footer that would appear after all the previous items, then do you need to do subtraction?

  • Position 0 = > User 0
  • Position 1 = > User1
  • Location N = > User N
  • Location N + 1 = > footer

It is best to return only mUsers.get(position).

EDIT: One more small question:

Here’s a question:

private boolean isFooterPosition(int position) {
    return position == mUsers.size() + 1;
}

mUsers.size() is 20, so the user’s position is 0-19.
isFooterPosition should return true for 20 (user size + 1). However, this will return false because the footer is at position 21.

Therefore, you have a point that is completely invalid (20).

private boolean isFooterPosition(int position) {
    return position == mUsers.size();
}

Related Problems and Solutions