【问题标题】:Shared prefrence overwrites共享首选项覆盖
【发布时间】:2015-08-08 17:38:35
【问题描述】:

我将一个字符串集保存在加载到我的关注列表的共享首选项中。当用户单击电影页面中的按钮时,它会获取电影的名称、标题和发行日期,并将它们存储在 JSON 对象中。所有这些都存储为字符串。当我尝试在监视列表中添加一部电影时,问题仍然存在,我添加的每一部新电影,最后一部电影都会被覆盖,这意味着我的监视列表中始终只能有一部电影。

mButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            SharedPreferences sharedPreferences = getSharedPreferences("WatchlistData", Context.MODE_PRIVATE);
            SharedPreferences.Editor editor = sharedPreferences.edit();

            JSONObject obj = new JSONObject();
            try {
                obj.put("name", name);
                obj.put("date", releaseDate);
                obj.put("platform", platform);
            } catch (JSONException e) {
                e.printStackTrace();
            }

            Set<String> set = new HashSet<String>();
            set.add(obj.toString());

            editor.putStringSet("setOfStrings", set);



            editor.commit(); //saved

        }
    });

监视列表片段 OnCreateView

  public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    View view = inflater.inflate(R.layout.fragment_watchlist, container, false);
    mRecyclerView = (RecyclerView) view.findViewById(R.id.watchlist);
    mRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
    mWatchlistAdapter = new WatchlistAdapter(getActivity(), loadFromStorage());
    mWatchlistAdapter.notifyDataSetChanged();
    mRecyclerView.setAdapter(mWatchlistAdapter);
    return view;
}

loadFromStorage,在recyclerview中加载我的xml文件,这个方法在我的适配器构造函数中传递。

SharedPreferences mPrefs = getActivity().getSharedPreferences("WatchlistData", Context.MODE_PRIVATE);

    ArrayList<watchlist> items = new ArrayList<watchlist>();

    Set<String> set = mPrefs.getStringSet("setOfStrings", null); //retrieving set of strings

    if (set == null){
        Toast.makeText(getActivity(), "No data found", Toast.LENGTH_LONG).show();
    } else {
        //for every string in set
        for (String s : set) {
            try {
                JSONObject jsonObject = new JSONObject(s); //for every JSONObject String
                String name = jsonObject.getString("name");
                String date = jsonObject.getString("date");
                String platform = jsonObject.getString("platform");

                watchlist newGame = new watchlist();

                newGame.setGame(name);
                newGame.setDate(date);
                newGame.setPlatform(platform);
                items.add(newGame);

            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    }

    return items;
}

【问题讨论】:

    标签: android sharedpreferences android-recyclerview


    【解决方案1】:

    默认情况下SharedPreferences 用新数据替换旧数据。您可以做的是,先获取旧数据,然后附加新数据,

    //Extract the value stored in SharedPreferences
    String value = prefs.getString(<Key>, <DefaultValue>);
    
    //Append to the extracted value
    String appendedValue = append(value, newValue);
    
    //Write the result back to SharedPreferences
    editor.putString(<Key>, appendedValue).commit();
    

    SharedPreferenced 用于轻量级数据,但不适用于大量存储。因此,根据您的要求,您应该将数据写入外部存储中的 JSON/XML 文件,然后再将其读回。

    【讨论】:

    • 你能给我一个关于在外部存储中保存为 JSON/XML 的教程吗?
    【解决方案2】:

    看起来你每次在 SharedPreferences 中放东西时只是覆盖了字符串集,这就是为什么你只看到最后一个结果:

            Set<String> set = new HashSet<String>();
            set.add(obj.toString());
    
            editor.putStringSet("setOfStrings", set);
    

    每次点击都会为您创建一个新的“集合”并将其保存到“setOfStrings”。

    我自己正在考虑为一个项目使用类似的实现,但发现从 SharedPreferences 操作 StringSet 成为一个问题。供参考,[Android 开发者网站上的文档](http://developer.android.com/reference/android/content/SharedPreferences.html#getStringSet(java.lang.String, java.util.Set)) 状态, “请注意,您不得修改此调用返回的集合实例。如果您这样做,则无法保证存储数据的一致性,您也无法修改该实例。”

    对此有一些解决方法,但据我了解,最好避免将 SharedPreferences 用于此类经常被操作的数据,因为它只是保存为容易出现问题的 xml 文件 - 您可能需要考虑在 SQLite 数据库中实现该信息。

    【讨论】:

    • 你能给我一个关于在外部存储中保存为 JSON/XML 的教程吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-09-08
    • 1970-01-01
    • 2019-11-15
    • 1970-01-01
    相关资源
    最近更新 更多