I am trying to save recyclerview entries in shared preferences as favorites. I want to implement favorites button with each entry of recyclerview. I have already completed design part. My code also working perfectly for adding entries in shared preferences and showing it in "FavoritesActivity" through recyclerview.

My problem:

  1. Remove from favorites not working
  2. My entries doesn't feel heart icon (Means, not showing as favorite) which entries are already in favorites.

I tried a lot and tested various codes. I also search stackoverflow and other sites but sad :(

MySharedPreference class

public class MySharedPreference {

    public static final String PREFS_NAME = "MY_APP";
    public static final String FAVORITES = "Profile_Favorite";

    public MySharedPreference() {
        super();
    }

    // This four methods are used for maintaining favorites.
    public void saveFavorites(Context context, List<ProfileModel> favorites) {
        SharedPreferences settings;
        Editor editor;

        settings = context.getSharedPreferences(PREFS_NAME,
                Context.MODE_PRIVATE);
        editor = settings.edit();

        Gson gson = new Gson();
        String jsonFavorites = gson.toJson(favorites);

        editor.putString(FAVORITES, jsonFavorites);

        editor.apply();
    }

    public void addFavorite(Context context, ProfileModel ProfileModel) {
        List<ProfileModel> favorites = getFavorites(context);
        if (favorites == null)
            favorites = new ArrayList<ProfileModel>();
        favorites.add(ProfileModel);
        saveFavorites(context, favorites);
    }

    public void removeFavorite(Context context, ProfileModel ProfileModel) {
        ArrayList<ProfileModel> favorites = getFavorites(context);
        if (favorites != null) {
            favorites.remove(ProfileModel);
            saveFavorites(context, favorites);
        }
    }

    public ArrayList<ProfileModel> getFavorites(Context context) {
        SharedPreferences settings;
        List<ProfileModel> favorites;

        settings = context.getSharedPreferences(PREFS_NAME,
                Context.MODE_PRIVATE);

        if (settings.contains(FAVORITES)) {
            String jsonFavorites = settings.getString(FAVORITES, null);
            Gson gson = new Gson();
            ProfileModel[] favoriteItems = gson.fromJson(jsonFavorites,
                    ProfileModel[].class);

            favorites = Arrays.asList(favoriteItems);
            favorites = new ArrayList<ProfileModel>(favorites);
        } else
            return null;

        return (ArrayList<ProfileModel>) favorites;
    }
}

My Adapter

public class ProfileAdapter extends RecyclerView.Adapter<ProfilePostAdapter.PostViewHolder> {

    MySharedPreference mySharedPreference;
    private Context context;
    List<ProfileModel> items;

    public ProfileAdapter(Context context, List<ProfileModel> items) {
        this.context = context;
        this.items = items;
        mySharedPreference = new MySharedPreference();
    }

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

    @Override
    public void onBindViewHolder(final PostViewHolder holder, final int position) {
        final ProfileModel item = items.get(position);
        holder.profileID.setText(item.getId());
        holder.profileTitle.setText(item.getTitle());
        holder.profileDescription.setText(document.text());

        if (checkFavoriteItem(item)) {
            holder.mFavIcon.setImageResource(R.drawable.ic_fav_filled);
            holder.mFavIcon.setTag("red");
        } else {
            holder.mFavIcon.setImageResource(R.drawable.ic_fav_blank);
            holder.mFavIcon.setTag("grey");
        }

        Document document = Jsoup.parse(item.getContent());

        holder.itemView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(context, ProfileDetailActivity.class);
                intent.putExtra("title", item.getTitle());
                intent.putExtra("description", item.getDescription());
                intent.putExtra("Id", item.getId());

                context.startActivity(intent);
            }

        });

        holder.mFavoriteButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                ImageView button = v.findViewById(R.id.img_fav_profile);

                String tag = button.getTag().toString();
                if (tag.equals("grey")) {
                    mySharedPreference.addFavorite(context, items.get(position));
                    Toast.makeText(context,
                            v.getResources().getString(R.string.add_favr),
                            Toast.LENGTH_SHORT).show();

                    button.setTag("red");
                    button.setImageResource(R.drawable.ic_fav_filled);
                }
                else if (tag.equals("red")) {
                    mySharedPreference.removeFavorite(context, items.get(position));
                    Toast.makeText(context,
                            v.getResources().getString(R.string.remove_favr),
                            Toast.LENGTH_SHORT).show();

                    button.setTag("grey");
                    button.setImageResource(R.drawable.ic_fav_blank);
                }
            }
        });
    }

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

    class PostViewHolder extends RecyclerView.ViewHolder {
        TextView profileTitle;
        TextView profileDescription;
        TextView profileID;

        PostViewHolder(View itemView) {
            super(itemView);
            profileTitle = itemView.findViewById(R.id.profileTitle);
            profileDescription = itemView.findViewById(R.id.profileDescription);
            mFavoriteProfile = itemView.findViewById(R.id.img_fav_profile);
            profileID = itemView.findViewById(R.id.profileID);
        }
    }

    public boolean checkFavoriteItem(ProfileModel checkProfile) {
        boolean check = false;
        List<ProfileModel> favorites = mySharedPreference.getFavorites(context);
        if (favorites != null) {
            for (ProfileModel profile : favorites) {
                if (profile.equals(checkProfile)) {
                    check = true;
                    break;
                }
            }
        }
        return check;
    }
}

FavoriteActivity

public class FavoriteActivity extends AppCompatActivity {
    Toolbar mToolbar;
    MySharedPreference mySharedPreference;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        final ListView favoriteList;
        final MySharedPreference myshrdprefernces;
        final List<ProfileModel> favorites;
        final ProfileFavAdapter fnladpter;

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_profile_favorite);

        mToolbar = (Toolbar) findViewById(R.id.profile_fav_page_toolbar);
        setSupportActionBar(mToolbar);
        getSupportActionBar().setTitle("Favorites");
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);

        myshrdprefernces = new MySharedPreference();
        favorites = myshrdprefernces.getFavorites(FavoriteActivity.this);

        if (favorites == null) {
            showAlert(getResources().getString(R.string.no_favorites_items),
                    getResources().getString(R.string.no_favorites_msg));
        } else {

            if (favorites.size() == 0) {
                showAlert(
                        getResources().getString(R.string.no_favorites_items),
                        getResources().getString(R.string.no_favorites_msg));
            }


            favoriteList = (ListView) findViewById(R.id.list_product);
            if (favorites != null) {
                fnladpter = new ProfileFavAdapter(FavoriteActivity.this, favorites);
                favoriteList.setAdapter(fnladpter);

                favoriteList.setOnItemClickListener(new AdapterView.OnItemClickListener() {

                    public void onItemClick(AdapterView<?> parent, View arg1,
                                            int position, long arg3) {

                    }
                });

                favoriteList
                        .setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {

                            @Override
                            public boolean onItemLongClick(
                                    AdapterView<?> parent, View view,
                                    int position, long id) {

                                ImageView button = (ImageView) view
                                        .findViewById(R.id.img_fav_profile);

                                String tag = button.getTag().toString();
                                if (tag.equalsIgnoreCase("no")) {
                                    myshrdprefernces.addFavorite(FavoriteActivity.this,
                                            favorites.get(position));
                                    Toast.makeText(
                                            FavoriteActivity.this,
                                            getString(
                                                    R.string.add_favr),
                                            Toast.LENGTH_SHORT).show();

                                    button.setTag("red");
                                    button.setImageResource(R.drawable.ic_fav_filled);
                                } else {
                                    myshrdprefernces.removeFavorite(FavoriteActivity.this,
                                            favorites.get(position));
                                    button.setTag("grey");
                                    button.setImageResource(R.drawable.ic_fav_blank);
                                    fnladpter.remove(favorites.get(position));
                                    Toast.makeText(
                                            FavoriteActivity.this,
                                            getString(
                                                    R.string.remove_favr),
                                            Toast.LENGTH_SHORT).show();
                                }
                                return true;
                            }
                        });
            }
        }
    }

Please guide me what is going wrong? I really tried a lot. Once again, everything is working fine just 2 problems.

  1. When I click on FavoriteActivity's recyclerview, its removing item from recyclerview but when I close activity and open it again, its appearing. Means, actually its not removing.

  2. My adapter not showing entries as favorite (means, filled heart icon).

Thanks in advance.

0 Answers