javaandroidadapterandroid-adapterandroid-adapterview

public void onBindViewHolder(MyViewHolder myViewHolder, int position)


Help me, i dont know why it is still get the error: Do not treat position as fixed; only use immediately and call myViewHolder.getAdapterPosition() to look it up later

Here is my code

public void onBindViewHolder(MyViewHolder myViewHolder, int position) {
    JPGCreationActivity.this.pos = position;
    myViewHolder.imgPhoto.setImageBitmap(BitmapFactory.decodeFile(this.data.get(position)));
    myViewHolder.tvImageName.setText(new File(this.data.get(position)).getName());
    myViewHolder.itemView.setOnClickListener(new View.OnClickListener() {
        public void onClick(View view) {
            Intent intent = new Intent(MyAlbumAdapter.this.mContext, FullScreenViewActivity.class);
            intent.putExtra("ImagePosition", position);
            intent.putStringArrayListExtra("arraylist", MyAlbumAdapter.this.data);
            MyAlbumAdapter.this.mContext.startActivity(intent);
        }
    });
}

I've already read some questions about this problem in stackoverflow, but i cant find the solution for my project, it alerts in int position, i've try to read other code from many people who post online, and they all coded like me public void onBindViewHolder(MyViewHolder myViewHolder, int position).

Help me please!!!!!


Solution

  • Which line is the error on?

    If had to guess it is because you are using "position" in the clickListener, try using myViewHolder.getAdapterPosition() there.

    The position parameter changes all the time and can't be relied on to accurately map a position in the list.

    e.g. You have a list of 10 items and only 4 are displayed on the screen at one time, the position you will see will always be 0 through 3. As RecyclerView recycles its view holders and rebinds data. That is why you have to use getAdapterPosition, as that will give you the position you intuitively expect to see. Like if you scroll to the end of your list, you can expect getAdapterPosition to return 10 while the position parameter would likely be 3 at that point, since one of the 4 view holders is being recycled to display different data.

    Looking at your code I don't think you really want to be using the position parameter anywhere that you are using it. Replace them all with getAdapterPosition()