Search code examples
androidandroid-recyclerviewandroid-cardview

How to check the text that is already in RecyclerView or not


public class ChatsFragment extends Fragment {
    public static final String TITLE = "Chats";

FirebaseDatabase database;
DatabaseReference myRef;
List<Listdata> list;
RecyclerView recyclerview;

public static ChatsFragment newInstance() {

    return new ChatsFragment();
}

public View onCreateView(LayoutInflater inflater, ViewGroup group, Bundle b) {
    View view = inflater.inflate(R.layout.fragment_chats, group, false);
    recyclerview = view.findViewById(R.id.rview);
    database = FirebaseDatabase.getInstance();
    myRef = database.getReference("message");
    myRef.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            list = new ArrayList<>();
            for (DataSnapshot dataSnapshot1 : dataSnapshot.getChildren()) {

                UserDetails userdetails = dataSnapshot1.getValue(UserDetails.class);
                Listdata listdata = new Listdata();
                String name = userdetails.getName();
                String message = userdetails.getMessage();
                listdata.setName(name);
                listdata.setMessage(message);
                list.add(listdata);

            }

            RecyclerviewAdapter recycler = new RecyclerviewAdapter(list);
            RecyclerView.LayoutManager layoutmanager = new LinearLayoutManager(getContext());
            recyclerview.setLayoutManager(layoutmanager);
            recyclerview.setItemAnimator(new DefaultItemAnimator());
            recyclerview.setAdapter(recycler);

        }

        @Override
        public void onCancelled(DatabaseError error) {

        }
    });

    return view;
}
}

I have a recycler CardView with a list of names.The names sent by the firebase database. When I sent the same name twice it shows count 2.I want to check a name that is already listed or not. If the name is already in RecyclerView I want to show the count 2. How to check the name list and show the count.


Solution

  • Here is your answer:

    for (DataSnapshot dataSnapshot1 : dataSnapshot.getChildren()) {
    
                UserDetails userdetails = dataSnapshot1.getValue(UserDetails.class);
                String name = userdetails.getName();
                String message = userdetails.getMessage();
    
                if (list.contains(new ListData(name,message))) {
                   list.set(list.indexOf(new ListData(name, message)), new ListData(name + "check", message);
                } else {
                   list.add(new ListData(name, message));
                }
        }
    

    In Place of "2" you can code for incrementing of count. I considered message as a count