I'm getting this error when i'm implementing footer within recycler view.
This is how i have done it. I was using two types for showing different views in list, but something is not set well in method getItemCount()
or maybe when i'm getting position of clicked item model in list.
This is what i have so far:
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 for normal holder view in list and one item for footer view.
mUsers.get(position - 1);
will crash when the position
is 0 because you're looking for the item at index -1
which is invalid.
If you're adding a footer, which will be present after all of the previous items, then do you need do the substraction?
It might be better to just return mUsers.get(position)
.
Edit: There's another small issue:
Here's an issue:
private boolean isFooterPosition(int position) {
return position == mUsers.size() + 1;
}
mUsers.size()
is 20, so users will have positions 0-19.
isFooterPosition
should return true for 20 (users size + 1). However, that will return false
because the footer is at position 21
.
Thus, you have a spot (20
) that is completely invalid.
private boolean isFooterPosition(int position) {
return position == mUsers.size();
}
I think you can modify getUser()
method like following:
private boolean isValidPos(int position){
return position >= 0 && position < mUsers.size();
}
private User getUser (int position) {
if (isFooterPosition(position)) return null;
return isValidPos(position) ? mUsers.get(position) : null;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With