Click here to Skip to main content
15,886,724 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I'm trying to established in my application feature for users to add items from list as favorite and to retrieve data from SharedPreferences where i'm storing favorites to the another activity.

I have written one class where i'm maintaining all methods for adding, removing and saving items for favorites, but the problem is that when i click to add favorite and scroll down to list and come back, favorite icon losses and always returning false in adapter where i'm checking through one method if item exists in favorites SharedPreferences and returning appropriate icon for that.

Here is what i have done so far:

THIS IS THE CLASS FOR MAKING FUNCTIONALITY OF FAVORITES

Java
public class SharedPreference {

    public static final String PREFS_NAME = "GIFT_APP";
    public static final String FAVORITES  = "GIFTS";

    public SharedPreference() {
        super();
    }

    // THIS FOUR METHODS ARE USED FOR MAINTAINING FAVORITES.
    public void saveFavorite(Context context, List<GiftItem> giftItems) {

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

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

        editor.putString(FAVORITES, jsonFavorites);
        editor.apply();

    }

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

    public void removeFavorite(Context context, GiftItem giftItem) {
        ArrayList<GiftItem> favorites = getFavorites(context);
        if (favorites != null) {
            favorites = new ArrayList<>();
            favorites.remove(giftItem);
            saveFavorite(context, favorites);
        }
    }

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

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

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

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


THIS IS THE ADAPTER WHERE I'M SETTING TO IMAGE VIEW, WHICH ICON BASED ON STATE SHOULD SHOW IF ITEM EXISTS IN FAVORITE

Java
if (checkFavoriteItem(item)) {
            customViewHolder.iconFavorite.setImageResource(R.drawable.ic_favorite);
            customViewHolder.iconFavorite.setTag("red");
        } else {
            customViewHolder.iconFavorite.setImageResource(R.drawable.ic_add_favorite);
            customViewHolder.iconFavorite.setTag("red_empty");
        }


THIS IS THE METHOD IN ADAPTER FOR CHECKING IF ITEM OBJECT EXISTS IN FAVORITES

Java
public boolean checkFavoriteItem(GiftItem giftItem) {
        boolean check = false;
        List<GiftItem> favorites = sharedPreference.getFavorites(mContext);
        if (favorites != null) {
            for (GiftItem item : favorites) {
                if (item.equals(giftItem)) {
                    check = true;
                    break;
                }
            }
        }
        return check;
    }



AND THIS IS AN ACTIVITY WHERE I'M ADDING ITEM TO FAVORITE ON LONG CLICK LISTENER:

Java
@Override
            public void onLongClick(View view, int position) {
                ImageView button = (ImageView) view.findViewById(R.id.favorite);

                String tag = button.getTag().toString();
                if (tag.equalsIgnoreCase("red_empty")) {
                    sharedPreference.addFavorite(HomeActivity.this, giftItems.get(position));
                    Toast.makeText(HomeActivity.this, "Gift added to favorite",
                            Toast.LENGTH_SHORT).show();
                    button.setTag("red");
                    button.setImageResource(R.drawable.ic_favorite);
                } else {
                    sharedPreference.removeFavorite(HomeActivity.this, giftItems.get(position));
                    Toast.makeText(HomeActivity.this, "Gift removed from favorite",
                            Toast.LENGTH_SHORT).show();
                    button.setTag("red_empty");
                    button.setImageResource(R.drawable.ic_add_favorite);
                }
            }


THIS IS AN ACTIVITY WHERE SHOULD I SEE LIST OF FAVORITE ITEMS:

Java
public class GiftsFavoriteList extends AppCompatActivity {

    RecyclerView favoriteList;
    SharedPreference sharedPreference;
    List<GiftItem> favorites;
    FavoriteListAdapter adapter;
    AVLoadingIndicatorView loadingBar;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_gifts);

        initToolbar();
        loadingBar = (AVLoadingIndicatorView) findViewById(R.id.loading_bar);
        loadingBar.setVisibility(View.GONE);

        // Get favorite items from SharedPreferences.
        sharedPreference = new SharedPreference();
        favorites = sharedPreference.getFavorites(GiftsFavoriteList.this);

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

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

            favoriteList = (RecyclerView) findViewById(R.id.list);
            favoriteList.setLayoutManager(new LinearLayoutManager(this));

            if (favorites != null) {
                adapter = new FavoriteListAdapter(this, favorites);
                favoriteList.setAdapter(adapter);
                favoriteList.addOnItemTouchListener(new RecyclerTouchListener(GiftsFavoriteList.this, favoriteList, new ClickListener() {
                    @Override
                    public void onClick(View view, int position) {

                    }

                    @Override
                    public void onLongClick(View view, int position) {

                    }
                }));
            }
        }
    }

    private void initToolbar() {
        Typeface font   = Typeface.createFromAsset(getAssets(), "Cutie Patootie.ttf");
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        TextView titleToolbar = (TextView) toolbar.findViewById(R.id.title);
        titleToolbar.setTypeface(font);
        titleToolbar.setText(getString(R.string.toolbar_favorites));
        setSupportActionBar(toolbar);
    }

    public interface ClickListener {
        void onClick(View view, int position);

        void onLongClick(View view, int position);
    }

    public static class RecyclerTouchListener implements RecyclerView.OnItemTouchListener {

        private GestureDetector gestureDetector;
        private GiftsFavoriteList.ClickListener clickListener;

        public RecyclerTouchListener(Context context, final RecyclerView recyclerView, final GiftsFavoriteList.ClickListener clickListener) {
            this.clickListener = clickListener;
            gestureDetector = new GestureDetector(context, new GestureDetector.SimpleOnGestureListener() {
                @Override
                public boolean onSingleTapUp(MotionEvent e) {
                    return true;
                }

                @Override
                public void onLongPress(MotionEvent e) {
                    View child = recyclerView.findChildViewUnder(e.getX(), e.getY());
                    if (child != null && clickListener != null) {
                        clickListener.onLongClick(child, recyclerView.getChildPosition(child));
                    }
                }
            });
        }

        @Override
        public boolean onInterceptTouchEvent(RecyclerView rv, MotionEvent e) {

            View child = rv.findChildViewUnder(e.getX(), e.getY());
            if (child != null && clickListener != null && gestureDetector.onTouchEvent(e)) {
                clickListener.onClick(child, rv.getChildPosition(child));
            }
            return false;
        }

        @Override
        public void onTouchEvent(RecyclerView rv, MotionEvent e) {
        }

        @Override
        public void onRequestDisallowInterceptTouchEvent(boolean disallowIntercept) {

        }
    }

    public void showAlert(String title, String message) {
        AlertDialog.Builder builder = new AlertDialog.Builder(GiftsFavoriteList.this);
        builder.setTitle(title);
        builder.setMessage(message);
        builder.setCancelable(true);
        builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.cancel();
            }
        });
        builder.show();
    }
}



So i'm not getting any error here. I just want to save state when i add item to favorites. When i long click on item, icon changed drawable for as it should looks when it's added to favorite, but it looses that state when i scroll down to list and go back up.
Posted
Updated 28-Jan-16 22:17pm
v4
Comments
Member 14653157 28-Dec-19 11:56am    
Please i went Recyclerview adapter class full code

You should overriding method "equals" of your java bean by check primary key, I think so!
 
Share this answer
 
Comments
Member 12084016 29-Jan-16 4:15am    
Nope, nothing's change. If i scroll down and go back, recycler deselect favorite or if i exit the app and come back it's also deselect favorite. And if i go to the activity where should i see list of favorites i'm getting no items in favorites. I will update that activity now.
Noted that you are saving to preference only if the favorites == null. Try adding a Unique ID to the GiftItem so that you can match it to the item in the share preference, instead of checking for GiftItem.equals check if the ids are equal.
 
Share this answer
 
Comments
Member 12084016 29-Jan-16 12:10pm    
I'm saving it to preference if user long clicked on item.
Member 12801748 1-Sep-17 4:52am    
hukunaa matataaa?

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900