I have strange behaviour in my recyclerview which i can not figure out. I am using following code in my OnBindViewHolder()
@Override
public void onBindViewHolder(@NonNull ProductAdapter.OurViewHolder viewHolder, int i) {
Product currentItem = adapterData.get(i);
viewHolder.productNamesFragmentItemsBinding.setProductName(currentItem);
if (currentItem.getPhotoUris() != null) {
Picasso.get().load(currentItem.getPhotoUris().get(0))
.into(viewHolder.productNamesFragmentItemsBinding.ivProductImage);
}
if (mViewModel.isCartContainsThisProduct(currentItem.getIdProducts())) {
System.out.println("calling is cart contains");
viewHolder.productNamesFragmentItemsBinding.btnAddToCart.setVisibility(View.GONE);
viewHolder.productNamesFragmentItemsBinding.btnAdded.setVisibility(View.VISIBLE);
viewHolder.productNamesFragmentItemsBinding.btnCancel.setVisibility(View.VISIBLE);
} else {
System.out.println("calling cart not contains");
viewHolder.productNamesFragmentItemsBinding.btnAddToCart.setVisibility(View.VISIBLE);
viewHolder.productNamesFragmentItemsBinding.btnAdded.setVisibility(View.GONE);
viewHolder.productNamesFragmentItemsBinding.btnCancel.setVisibility(View.GONE);
}
}
I have five items in my adapter , at position 2 there is no url, still it loads the image sometimes but not always.
One more thing i noticed that there is a button "Add to cart", which refresh item at this position when clicked. So if i click this button at any position say at position 5, then again if i click at position 2 (where i have no url), image of position 5 loads at 2.
Its not strange behavior at all . This is how RecyclerView
works its basically reuse the same ViewHolder
for next items.
The problem with your code you have covers if (currentItem.getPhotoUris() != null)
case you have missed the else
part i.e clearing the image or setting a placeholder.
if (!TextUtils.isEmpty(currentItem.getPhotoUris())) {
Picasso.get().load(currentItem.getPhotoUris().get(0))
.into(viewHolder.productNamesFragmentItemsBinding.ivProductImage);
}else{
// you can set a placeholder image here
viewHolder.productNamesFragmentItemsBinding.ivProductImage.setImageResource(0)
}