Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android: Recycler view item fast clicking it crash the application

I have search a lot what I did is created a list of items simple number and having check box Which is checked and unchecked, So when I tap fast fast on list it crash and generate ArrayIndexOutOfBound Exception

So I don't know what is I am doing wrong

here is my code

adapter class

  class SingleListItemHolder extends RecyclerView.ViewHolder implements View.OnClickListener {

private TextView mItemDate, mFontSizeCategory;
    private ImageView isChecked, isTrack, isUnChecked;
    private int fontSize = 13;
SingleListItemHolder(View v) {
    super(v);
    mFontSizeCategory = (TextView) v.findViewById(R.id.tv_font_size_category);
    mItemDate = (TextView) v.findViewById(R.id.tv_recycler_view_list_header);
    isChecked = (ImageView) v.findViewById(R.id.iv_recycler_view_list_item_selected);
    isUnChecked = (ImageView) v.findViewById(R.id.iv_recycler_view_list_item_unselected);
    isTrack = (ImageView) v.findViewById(R.id.iv_track);
    v.setOnClickListener(this);
    this.setIsRecyclable(false);
}

@Override
public void onClick(View v) {
    mSingleItemListModels.get(pos).setSelected(false);
    notifyItemChanged(pos, mSingleItemListModels.get(pos));
    pos = getAdapterPosition();
    mSingleItemListModels.get(pos).setSelected(true);
    notifyItemChanged(pos, mSingleItemListModels.get(pos));
}
like image 723
kamlesh vora Avatar asked Dec 07 '22 16:12

kamlesh vora


2 Answers

pos = getAdapterPosition();

move above

mSingleItemListModels.get(pos).setSelected(false);
like image 107
Aytek Sökmen Avatar answered Dec 10 '22 11:12

Aytek Sökmen


You are getting -1 Position in getAdapterPosition() because when u are click fast it some time throw the -1 position

You can check this out

if (pos != RecyclerView.NO_POSITION) {
//Do your setting part
}

Change this code

@Override
public void onClick(View v) {
    mSingleItemListModels.get(pos).setSelected(false);
    notifyItemChanged(pos, mSingleItemListModels.get(pos));
    pos = getAdapterPosition();
    mSingleItemListModels.get(pos).setSelected(true);
    notifyItemChanged(pos, mSingleItemListModels.get(pos));
}

Code to

@Override
public void onClick(View v) {
    mSingleItemListModels.get(pos).setSelected(false);
    notifyItemChanged(pos, mSingleItemListModels.get(pos));
    pos = getAdapterPosition();
     if (pos != RecyclerView.NO_POSITION) {
        mSingleItemListModels.get(pos).setSelected(true);
        notifyItemChanged(pos, mSingleItemListModels.get(pos));
     }
}
like image 33
Amjad Khan Avatar answered Dec 10 '22 11:12

Amjad Khan