Item gets duplicated in recycler when follow button of an item is clicked

Published

The issue i’m facing is that after getting data from firebase(real time database) and placing that data in an adapter and then passing that to the recycler view,my item view consist of a user’s name,picture and a follow button that lets the user follow or unfollow the searched user.The issue is that when the follow button in the item view is clicked,immediately the onclick is executed and the button changes it’s text to "unfollow" that item gets duplicated in the recycler view instantly,if i exit the app and seach the same user and i attempt to click the follow button my app crashes,because from that point on wards the part of the object holding the data of all users following the searched user is null(i don’t understand why this happens because only the hashmap containing all users following the searched user is affected,the searched user picture and username returns data from firebase normally).
So what i want i need is that i do not want the item to get duplicated after clicking the follow button.
here’s my code:

the data repository for getting the queried data from firebase:

public MutableLiveData<List<Follower>> getUserQuery(MutableLiveData<String> name){
        getQuery(name);
        MutableLiveData<List<Follower>> data = new MutableLiveData<>();
        data.setValue(userQuery);
        return data;
    }

    private void getQuery(MutableLiveData<String> name){

        firebaseUser = FirebaseAuth.getInstance().getCurrentUser();
        reference= FirebaseDatabase.getInstance().getReference();
        firestore = FirebaseFirestore.getInstance();
        Query query= reference.child("users").orderByChild("userName").equalTo(name.getValue());
        query.addListenerForSingleValueEvent(new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot snapshot) {
               userQuery.clear();
                for (DataSnapshot Snapshot : snapshot.getChildren()) {
                    user = Snapshot.getValue(User.class);
                    reference.child("FollowerList").child(user.getUserID()).addValueEventListener(new ValueEventListener() {
                        @Override
                        public void onDataChange(@NonNull DataSnapshot snapshot) {
                            FL = snapshot.getValue(FollowerList.class);
                            Follower F = new Follower(FL.getFollowersList(), user.getUserID(), user.getUserName(), user.getImageProfile());
                            userQuery.add(F);


                        }

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

                        }
                    });


                }
            }

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

            }

        });
    }

ViewModel

public class SearchViewModel extends ViewModel {
    private MutableLiveData<List<Follower>> SearchedUsers;
    private SearchFragmentRepository mRepo;
    public  MutableLiveData<String> SearchName=new MutableLiveData<>();

    public void init(){
        if(SearchedUsers != null){
            SearchedUsers.setValue(null);
        }

        mRepo= SearchFragmentRepository.getInstance();
        SearchedUsers= mRepo.getUserQuery(SearchName);
    }

    public LiveData<List<Follower>> getSearchedUsers(){
        return SearchedUsers;
    }
}

Adapter

public class SearchListAdapter extends RecyclerView.Adapter<SearchListAdapter.MyViewHolder> {
    private List<Follower> followerList;
    private FirebaseUser firebaseUser;
    private FirebaseAuth mAuth;
    Context context;

    public SearchListAdapter(Context context,List<Follower> followerList){
        this.context=context;
        this.followerList=followerList;

    }

    public class MyViewHolder extends RecyclerView.ViewHolder {
        private TextView userName;
        private CircularImageView profileImage;
        private Button follow;
        public MyViewHolder(@NonNull View itemView){
            super(itemView);
            userName= itemView.findViewById(R.id.username);
            profileImage= itemView.findViewById(R.id.image_profile);
            follow=itemView.findViewById(R.id.follow_button);
        }
    }


    @NonNull
    @Override
    public MyViewHolder onCreateViewHolder(@NonNull ViewGroup parent,int viewType){
        LayoutInflater inflater= LayoutInflater.from(context);
        View view = inflater.inflate(R.layout.search_list,parent,false);
        return new MyViewHolder(view);

    }


    @Override
    public void onBindViewHolder(@NonNull MyViewHolder holder, int position) {
          Follower follower=  followerList.get(position);
          holder.userName.setText(follower.getUserName());
        Glide.with(context).load(follower.getImageProfile()).into(holder.profileImage);
        mAuth = FirebaseAuth.getInstance();
        firebaseUser = FirebaseAuth.getInstance().getCurrentUser();
        HashMap<String,String> FL = follower.getFollowers();
        String nName = follower.getUserName();
        String Id= follower.getUserID();
        String ImageUri = follower.getImageProfile();
            if(FL != null) {
                if (FL.containsKey(firebaseUser.getUid())) {
                    holder.follow.setText("Unfollow");
                }
            }


        holder.follow.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(FL.containsKey(firebaseUser.getUid()) ==false){
                    FL.put(firebaseUser.getUid(),firebaseUser.getUid());
                    DatabaseReference mDatabase = FirebaseDatabase.getInstance().getReference();
                    mDatabase.child("FollowerList").child(follower.getUserID()).setValue(FL);
                    holder.follow.setText("Unfollow");
                    Follower F = new Follower(FL,Id,nName,ImageUri);
                    followerList.set(position,F);
                    notifyItemChanged(position);

                }
                else{
                    FL.remove(firebaseUser.getUid());
                    DatabaseReference mDatabase = FirebaseDatabase.getInstance().getReference();
                    //HashMap<String,String> FL = follower.getFollowers();
                    mDatabase.child("FollowerList").child(follower.getUserID()).setValue(FL);
                    holder.follow.setText("Follow");
                    Follower F = new Follower(FL,Id,nName,ImageUri);
                    followerList.set(position,F);
                    notifyItemChanged(position);

                }
            }
        });
            holder.itemView.setTag(followerList.get(position));
    }

    @Override
    public int getItemCount() {
        return followerList == null ? 0 : followerList.size();
    }

    @Override
    public long getItemId(int position){ return position;}

    @Override
    public int getItemViewType(int position){ return position;}
}

SearchFragment

 @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        //return inflater.inflate(R.layout.fragment_search, container, false);

        binding= DataBindingUtil.inflate(inflater,R.layout.fragment_search,container,false);



        binding.recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
        binding.recyclerView.setAdapter(searchListAdapter);



        searchViewModel= new ViewModelProvider(this).get(SearchViewModel.class);


        firebaseUser = FirebaseAuth.getInstance().getCurrentUser();
         //reference= FirebaseDatabase.getInstance().getReference();
        //firestore = FirebaseFirestore.getInstance();

        binding.imageButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String name = binding.searchUser.getText().toString();
                //showUsers(name);
                searchViewModel.SearchName.setValue(name);
                searchViewModel.init();
                searchViewModel.getSearchedUsers();
                searchListAdapter = new SearchListAdapter(getContext(),searchViewModel.getSearchedUsers().getValue());
                searchListAdapter.notifyDataSetChanged();

                //searchListAdapter.notifyItemInserted(0);



            }
                });



        return binding.getRoot();

    }

I actually cut out some parts in some of the code to avoid posting too much unnecessary code,but if you need more info i can edit the code.

Source: Android Questions

Published
Categorized as android, android-adapter, android-recyclerview, firebase, mvvm

Answers

Leave a Reply

Still Have Questions?


Our dedicated development team is here for you!

We can help you find answers to your question for as low as 5$.

Contact Us
faq