简体   繁体   中英

Multiple data when clicked item on recyclerview

I try to show chatlist but when i clicked item, list from recyclerview be duplicate looks like in picture 1, but when i change fragment (bottom nav) the list be normal (not duplicate). What's wrong with my code, please help

after item clicked before item clicked

here the code AdapterChatlist

public class AdapterChatlist extends RecyclerView.Adapter<AdapterChatlist.Holder>{
Context context;
List<User> userList;//get user info
private HashMap<String, String> lastMsgMap;
public AdapterChatlist(Context context, List<User> userList) {
    this.context = context;
    this.userList = userList;
    lastMsgMap = new HashMap<>();
}
@NonNull
@Override
public Holder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
    //inflate layout row_chatlist
    View view = LayoutInflater.from(context).inflate(R.layout.row_chatlist, parent, false);
    return new Holder(view);
}
@Override
public void onBindViewHolder(@NonNull Holder holder, int position) {
    String hisUid = userList.get(position).getId();
    String userImg = userList.get(position).getImageUrl();
    String userName = userList.get(position).getFullname();
    String lastMsg = lastMsgMap.get(hisUid);

    holder.nameTv.setText(userName);
    if (lastMsg==null || lastMsg.equals("default")){
        holder.lastMsgTv.setVisibility(View.GONE);
    }else {
        holder.lastMsgTv.setVisibility(View.VISIBLE);
        holder.lastMsgTv.setText(lastMsg);
    }
    try {
        Glide.with(context).load(userImg)
                .placeholder(R.drawable.ic_pic)
                .into(holder.profileIv);
    }catch (Exception e){
        Glide.with(context).load(R.drawable.ic_pic)
                .into(holder.profileIv);
    }
    if (userList.get(position).getOnlineStat().equals("online")){
        holder.onlineStatIv.setImageResource(R.drawable.ic_online);
    }else {
        holder.onlineStatIv.setImageResource(R.drawable.ic_offline);
    }
    holder.itemView.setOnClickListener(view -> {
        Intent intent = new Intent(context, MessageActivity.class);
        intent.putExtra("userid", hisUid);
        context.startActivity(intent);
    });
}
public void setLastMsgMap(String userId, String lastMsg){
    lastMsgMap.put(userId, lastMsg);
}

@Override
public int getItemCount() {
    return userList.size();
}
class Holder extends RecyclerView.ViewHolder{
    ImageView profileIv, onlineStatIv;
    TextView nameTv, lastMsgTv;

    public Holder(@NonNull View itemView) {
        super(itemView);
        profileIv = itemView.findViewById(R.id.profileIv);
        onlineStatIv = itemView.findViewById(R.id.onlineStatIv);
        nameTv = itemView.findViewById(R.id.nameTv);
        lastMsgTv = itemView.findViewById(R.id.lastMsgTv);
    }
}}

here code for ChatlistFragement

private void loadChats() {
    usersList = new ArrayList<>();
    ref = FirebaseDatabase.getInstance().getReference("Users");
    ref.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(@NonNull DataSnapshot snapshot) {
            for (DataSnapshot ds : snapshot.getChildren()) {
                User users = ds.getValue(User.class);
                for (Chatlist chatlist : chatlistList) {
                    if (users.getId() != null && users.getId().equals(chatlist.getId())) {
                        usersList.add(users);
                        break;
                    }
                }
                adapterChatlist = new AdapterChatlist(getContext(), usersList);
                //setAdapter
                rv_chatsList.setAdapter(adapterChatlist);
                //set last msg
                for (int i = 0; i < usersList.size(); i++) {
                    lastMsg(usersList.get(i).getId());
                }
            }
        }

        @Override
        public void onCancelled(@NonNull DatabaseError error) {

        }
    });
}

private void lastMsg(final String userId) {
    DatabaseReference reference = FirebaseDatabase.getInstance().getReference("Chats");
    reference.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(@NonNull DataSnapshot snapshot) {
            String theLastMsg = "default";
            for (DataSnapshot ds : snapshot.getChildren()) {
                Chat chat = ds.getValue(Chat.class);
                if (chat == null) {
                    continue;
                }
                String sender = chat.getSender();
                String receiver = chat.getReceiver();
                if (sender == null || receiver == null) {
                    continue;
                }
                if (chat.getReceiver().equals(currentUser.getUid()) && chat.getSender().equals(userId) ||
                        chat.getReceiver().equals(userId) && chat.getSender().equals(currentUser.getUid())) {
                    theLastMsg = chat.getMessage();
                }
            }
            adapterChatlist.setLastMsgMap(userId, theLastMsg);
            adapterChatlist.notifyDataSetChanged();
        }

        @Override
        public void onCancelled(@NonNull DatabaseError error) {

        }
    });
}

With "adapterChatlist.setLastMsgMap(userId, theLastMsg);" you are adding some new users to the already existing list. My guess is that you should have one list with all the items you want to show and always clear the old list that the adapter has. Because this onDataChange() probably gets called multiple times not only once, that's why you get more items.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM