如何将Recyclerview条目保存为共享首选项中的收藏夹?

时间:2019-05-12 17:02:15

标签: android android-recyclerview sharedpreferences

我正在尝试将共享首选项中的recyclerview条目保存为收藏夹。我想在每个recyclerview条目中实现“收藏夹”按钮。我已经完成了设计部分。我的代码还可以完美地用于在共享首选项中添加条目,并通过recyclerview在“ FavoritesActivity”中显示该条目。

我的问题:

  1. 从收藏夹中删除不起作用
  2. 我的条目没有心形图标(意味着,没有显示为收藏夹),这些条目已经在收藏夹中。

我尝试了很多,并测试了各种代码。我也搜索stackoverflow和其他网站,但很伤心:(

MySharedPreference类

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;
    }
}

我的适配器

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;
                            }
                        });
            }
        }
    }

请指导我怎么了?我真的尝试了很多。再一次,一切正常,只有两个问题。

  1. 当我单击FavoriteActivity的recyclerview时,将从recyclerview中删除该项目,但是当我关闭活动并再次打开它时,它就会出现。意思是,实际上它并没有消除。

  2. 我的适配器未将条目显示为收藏夹(均值,实心图标)。

谢谢。

0 个答案:

没有答案