在RecyclerView中使用滑动删除视图时未在SharedPreference中删除 [英] When Deleting View with Swipe in RecyclerView doesn't deletin in SharedPreference

查看:58
本文介绍了在RecyclerView中使用滑动删除视图时未在SharedPreference中删除的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试删除RecylerView中的通过滑动查看",我在SharedPreferences中保存了选中的带有收藏夹"按钮的视图.保存到SharedPreferences中的选定视图后,我尝试用向左滑动向内移除收藏夹" Activity,我完成了此操作,但是当我返回收藏夹Activity"时,我看到旧项目没有更新SharedPreferences向左滑动.

I am trying delete View with Swipe in RecylerView, I saved in SharedPreferences to selected View with favorite button. After I saved to selected View in SharedPreferences, I am trying remove Favorite Activity with Swipe to left ,I was done this but When I return Favorite Activity, I saw old items doesn't updated SharedPreferences When I swipe to left.

我该怎么做?

public class SharedPreference {

        public static final String PREFS_NAME = "NKDROID_APP";
        public static final String FAVORITES = "Favorite";

        public SharedPreference() {
            super();


        }


        public void storeFavorites(Context context, List<OrderModel> favorites) {
            SharedPreferences settings;
            SharedPreferences.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.commit();
        }

        public ArrayList<OrderModel> loadFavorites(Context context) {
            SharedPreferences settings;
            List<OrderModel> favorites;

            settings = context.getSharedPreferences(PREFS_NAME,Context.MODE_PRIVATE);
            if (settings.contains(FAVORITES)) {
                String jsonFavorites = settings.getString(FAVORITES, null);
                Gson gson = new Gson();
                OrderModel[] favoriteItems = gson.fromJson(jsonFavorites,OrderModel[].class);
                favorites = Arrays.asList(favoriteItems);
                favorites = new ArrayList<OrderModel>(favorites);
            } else
                return null;

            return (ArrayList<OrderModel>) favorites;
        }


        public void addFavorite(Context context, OrderModel beanSampleList) {
            List<OrderModel> favorites = loadFavorites(context);
            if (favorites == null)
                favorites = new ArrayList<OrderModel>();
            favorites.add(beanSampleList);
            storeFavorites(context, favorites);
        }

        public void removeFavorite(Context context, OrderModel beanSampleList) {
            ArrayList<OrderModel> favorites = loadFavorites(context);
            if (favorites != null) {
                favorites.remove(beanSampleList);
                storeFavorites(context, favorites);
            }
        }
    /*
        public void saveHighScoreList(String scoreString) {
            editor.putString(FAVORITES, scoreString);
            editor.commit();
        }

        public String getHighScoreList() {
            return settings.getString(FAVORITES, "");
        }
        */

    }




@Override
public void onSwiped(RecyclerView.ViewHolder viewHolder, int direction, int position) {

    if (viewHolder instanceof OrderAdapter.OrderViewHolder) {
        // get the removed item name to display it in snack bar
        String name = order_models.get(viewHolder.getAdapterPosition()).getOrder_name();


        final OrderModel deletedItem = order_models.get(viewHolder.getAdapterPosition());
        final int deletedIndex = viewHolder.getAdapterPosition();


        order_adapter.removeItem(viewHolder.getAdapterPosition());

        //remove from shared preferences
        sharedPreference.removeFavorite(Orders.this, deletedItem);
        order_models.remove(deletedItem);
        order_adapter.notifyDataSetChanged();

        Toast.makeText(Orders.this, "Success Remove",Toast.LENGTH_SHORT).show();

        // showing snack bar with Undo option
        Snackbar snackbar = Snackbar
                .make(constraint, name + " removed from cart!", Snackbar.LENGTH_LONG);
        snackbar.setAction("UNDO", new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                // undo is selected, restore the deleted item
                order_adapter.restoreItem(deletedItem, deletedIndex);
            }
        });
        snackbar.setActionTextColor(Color.YELLOW);
        snackbar.show();
    }

}

推荐答案

对于一个,您可能不应该每次查询或修改列表时都从首选项中加载收藏夹列表.而是在创建此RecyclerView所属的活动时查询一次(您可以从适配器本身或从活动中执行此操作),并将其存储到全局变量中.即:

For one, you probably shouldn't be loading the list of favorites from preferences every single time you want to query or modify the list. Instead, query it once when the Activity this RecyclerView belongs to is created (you could do that from the Adapter itself or from the Activity), and store that to a global variable. ie:

class SomeActivity extends Activity {
    private ArrayList<OrderModel> favorites = new ArrayList<>();
    private SharedPreference prefsHelper = new SharedPreference();

    @Override
    public void onCreate(Bundle savedInstanceState) {
        //....

        favorites.addAll(prefsHelper.loadFavorites(this));
    }
}

然后,当您要更改某些内容时,请修改该ArrayList,然后直接将其保存:

Then, when you want to change something, modify that ArrayList and then save it directly:

public void addFavorite(OrderModel model) {
    favorites.add(model);
    prefsHelper.storeFavorites(this, favorites);
}

您可能需要修改此代码以适合您的代码,但这只是操作示例.

You'll probably need to modify this to fit your code, but it's an example of what to do.

您当前无法使用的内容,因为每次您修改列表时,都是从String表示形式重新创建它.这意味着您加载的收藏夹列表包含完全不同的模型实例,即使它们包含相同的值.

What you currently have won't work, because every time you go to modify the list, you're recreating it from a String representation. That means that the list of favorites you have loaded contains completely different instances of the models, even if they contain the same values.

当您将OrderModel传递给您的removeFavorite()方法时,它不会删除任何内容,因为没有什么相等的.通过重新加载列表,您将拥有全新的实例.

When you pass an OrderModel to your removeFavorite() method, it's not going to remove anything, because nothing is equal; by reloading the list, you have completely fresh instances.

如果您确实要保留当前的代码结构,请切换到索引而不是传递对象.或者,在OrderModel中覆盖equals()并手动比较值,以便甚至可以匹配不同的实例.

If you really want to keep your current code structure, switch to indexes instead of passing the object. Or, override equals() in OrderModel and have it manually compare the values, so even different instances can be matched.

这篇关于在RecyclerView中使用滑动删除视图时未在SharedPreference中删除的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆