Search code examples
javaandroidandroid-studiopicasso

Error RecyclerView with Picasso Android


I have recyclerview that contains image.

@Override
    public void onBindViewHolder(ViewHolder viewHolder, final int position) {
        // Get element from your dataset at this position and replace the contents of the view
        // with that element
        if(mEntities.get(position).url.equals("kosong")) {
            Log.e("LOAD", "KOSONG " + position);
            viewHolder.getTextDataView().setText(mEntities.get(position).data);
        }
        else{
            Log.e("LOAD", "ISI " + position);
            Picasso.with(mContext).load(mEntities.get(position).url).skipMemoryCache().into(viewHolder.imageView);
            viewHolder.getTextDataView().setText(mEntities.get(position).data);          
        }
    }

Im success to make the image loaded to recyclerview in correct list, but somehow it duplicate in another list in that recyclerview. Why ?

Thanks for your answer :)


Solution

  • So from what I understand if your url contains "kosong" you shouldn't display any image right?

    However you're not clearing the imageview of it's previous image. Keep in mind that listviews/recycler views recycle their views. So if you display an image on your imageview and later on (scrolling up and down) that imageview is recycled it will contain the last image that was set to it.

    Remember to clear the image when you don't want to use it (if(mEntities.get(position).url.equals("kosong"))) using something like: viewHolder.imageView.setImageResource(android.R.color.transparent);

    So it should be something like this:

    if(mEntities.get(position).url.equals("kosong")) {
            Log.e("LOAD", "KOSONG " + position);
            viewHolder.getTextDataView().setText(mEntities.get(position).data);
            //we don't need to display an image here however it's possible that our listview contains another image from a recycled row. Let's clear it
            viewHolder.imageView.setImageResource(android.R.color.transparent);
        }
        else{
            Log.e("LOAD", "ISI " + position);
            Picasso.with(mContext).load(mEntities.get(position).url).skipMemoryCache().into(viewHolder.imageView);
            viewHolder.getTextDataView().setText(mEntities.get(position).data);          
        }