Abhinash Abhinash - 6 months ago 62
Android Question

RecyclerView duplicates some UI components

I'm trying to implement a

RecyclerView
in my app but some UI components in my
RecyclerView
keep repeating themselves when I scroll. It might be an issue with cache but I haven't implemented any logic for cache of UI elements. I'm also using the Picasso library.

Here's my code:

public class Adapter extends RecyclerView.Adapter<Adapter.ViewHolder> {
private List<CardViewBean> mListItemsCard;
Activity mActivity;
CardViewBean itemCardView;
ChatMessageDTO chatMessageDTO;
List<EventGalleryDTO> eventGalleryDTOs;
private static final String PICASSO_CACHE = "picasso-cache";

public Adapter(Activity activity, List<CardViewBean> listItemsCard) {
mListItemsCard = listItemsCard;
this.mActivity = activity;
}

@Override
public Adapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
return new ViewHolder(mActivity, LayoutInflater.from(parent.getContext()).inflate(R.layout.layout_adapter, parent, false));
}

@Override
public void onBindViewHolder(ViewHolder holder, int position) {
SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(mActivity);
itemCardView = mListItemsCard.get(position);
holder.txtEventName.setText(itemCardView.getEventName());
if (itemCardView.getMessageCount() > 0) {
holder.txtChat.setText("(" + itemCardView.getMessageCount() + ")");
}
if (itemCardView.getImageCount() > 0) {
holder.txtGallery.setText(String.valueOf(itemCardView.getImageCount()));
}
chatMessageDTO = getChatMsgDTO();
String imagePath = mListItemsCard.get(position).getImagePath();

if (StringUtils.isNotBlank(imagePath)) {
File file = new File(imagePath);
if (file.exists()) {
setCreatorImage(file, holder);
} else {
holder.ivEventImage.setImageResource(R.drawable.placeholder);
}
}

if (chatMessageDTO != null) {
if (StringUtils.isNotBlank(chatMessageDTO.getMessage())) {
holder.txtLastMessage.setText(chatMessageDTO.getMessage());
}

String time = "";
if (StringUtils.isNotBlank(chatMessageDTO.getDateTime())) {
String dateArr[] = chatMessageDTO.getDateTime().split(" ");
if (dateArr.length > 1) {
if (dateArr[1].contains(":")) {
time = dateArr[1].substring(0, dateArr[1].lastIndexOf(":"));
} else {
time = dateArr[1];
}
holder.txtLastMessageTime.setText(time);
}
}
}
}

@Override
public int getItemCount() {
return mListItemsCard.size();
}
}

Answer

Try this (add a else statement):

if (itemCardView.getMessageCount() > 0) {
    holder.txtChat.setText("(" + itemCardView.getMessageCount() + ")");
}

else {
    holder.txtChat.setText("")

}

if (itemCardView.getImageCount() > 0) {
    holder.txtGallery.setText(String.valueOf(itemCardView.getImageCount()));
}
else {
    holder.txtGallery.setText("")
}
Comments