Как сохранить записи переработчика как избранные в общих настройках? - PullRequest
0 голосов
/ 12 мая 2019

Я пытаюсь сохранить записи переработчика в общих настройках как избранные. Я хочу реализовать кнопку «Избранное» с каждой записью в программе. Я уже закончил дизайн части. Мой код также отлично работает для добавления записей в общих настройках и отображения его в «FavoritesActivity» через утилиту восстановления.

Моя проблема:

  1. Удалить из избранного не работает
  2. Мои записи не чувствуют значок сердца (означает, что они не отображаются как избранные), записи которых уже добавлены в избранное.

Я много пробовал и тестировал разные коды. Я также ищу stackoverflow и другие сайты, но грустно: (

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

Мой адаптер

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

Пожалуйста, объясните мне, что происходит? Я действительно много пробовал. Еще раз, все работает нормально, только 2 проблемы.

  1. Когда я нажимаю на представление переработчика FavoriteActivity, оно удаляет элемент из представления переработчика, но когда я закрываю действие и снова открываю его, оно появляется. Значит, на самом деле это не удаление.

  2. Мой адаптер не отображает записи в качестве избранных (значит, значок заполненного сердца).

Заранее спасибо.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...