繁体   English   中英

如何停止将arraylist多次放入共享的首选项文件中?

[英]How can I stop my arraylist being put multiple times into my shared preferences file?

arraylist的格式应为[{"12345"}, {"67890"}, etc...]

但是,当我关闭我的应用程序时-我的意思是按返回按钮的次数返回到Android主屏幕-然后重新启动它,我看到MatchingContactsAsArrayList[{"12345"}, {"67890"}, etc...,{"12345"}, {"67890"}, etc...]

如果关闭两次, arraylist会出现3次,依此类推,它会变得更长。 它应该只显示每个值一次。

我以为editorMatchingContactsAsArrayList.remove(jsonMatchingContactsAsArrayList).commit(); 会照顾这个。

这是我的代码:

        @Override
            public void onResponse(String response) {

                //convert the JSONArray, the response, to a string
                String MatchingContactsAsString = response.toString();

                //make an arraylist which will hold the phone_number part of the MatchingContacts string
                MatchingContactsAsArrayList = new ArrayList<String>();

                try {
                    JSONArray Object = new JSONArray(MatchingContactsAsString);
                    for (int x = 0; x < Object.length(); x++) {
                        final JSONObject obj = Object.getJSONObject(x);
                        MatchingContactsAsArrayList.add(obj.getString("phone_number"));

                    }

                    SharedPreferences sharedPreferencesMatchingContactsAsArrayList = PreferenceManager.getDefaultSharedPreferences(getApplication());
                    SharedPreferences.Editor editorMatchingContactsAsArrayList = sharedPreferencesMatchingContactsAsArrayList.edit();
                    Gson gsonMatchingContactsAsArrayList = new Gson();
                    String jsonMatchingContactsAsArrayList = gsonMatchingContactsAsArrayList.toJson(MatchingContactsAsArrayList);
                    editorMatchingContactsAsArrayList.putString("MatchingContactsAsArrayList", jsonMatchingContactsAsArrayList);
                    editorMatchingContactsAsArrayList.remove(jsonMatchingContactsAsArrayList).commit();
                    editorMatchingContactsAsArrayList.commit();

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


            }

SharedPreferences.remove()方法采用您以前保存的key

在这种情况下为“ MatchingContactsAsArrayList”。

实际上,您不需要使用remove() ,因为带有现有key putString()会覆盖该值。 请确保来自响应的数据是正确的。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM