Search code examples
androidfavorites

Adding to favorite doesn't persist state


I have a tour list in android and I am trying to implementing add to favorites. Favorite works for the list that is added in myTours but doesn't work for tours from search list.

This is the code:

private List<Tour> tourList;
holder.imgFavourite.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(tourList.get(position).getFav().equalsIgnoreCase("0")) {
                   tourList.get(position).setFav("1");
                  //  listener.onFavourited(tourList.get(position), true);
                    holder.imgFavourite.setImageResource(R.drawable.faved);
                } else {
                    tourList.get(position).setFav("0");
                  //  listener.onFavourited(tourList.get(position), false);
                    holder.imgFavourite.setImageResource(R.drawable.not_faved);
                }
            }
        });

Here when I click on Fav icon gets changed to faved. But if I search for different category and again come back to that category state doesn't persist.

Any help would be appreciated.


Solution

  • Listview/RecyclerView reuses views. If your list has 20 items and 4 are visible at one time, as you scroll, the views are reused to show the new visible views to save memory. So if you alter the view at position 5 and scroll down and scroll back up to position 5, the view that you changed in position 5 is not the same view that you are seeing after you scroll back up. Hence the view changes

    To fix this, maintain a global variable in the adapter which stores the favorite position and in the onBindViewHolder, add a condition like

    if(position = favPosition)
        <Change to fav view>
    else
        <Change to Normal View>
    

    The else condition is really important or else multiple views will have the Fav view