Java 如何阻止我的arraylist被多次放入共享首选项文件中?

Java 如何阻止我的arraylist被多次放入共享首选项文件中?,java,android,gson,android-sharedpreferences,Java,Android,Gson,Android Sharedpreferences,arraylist的格式应为,[{“12345”},{“67890”},等等..] 但是当我关闭我的应用程序时——我的意思是按后退按钮返回Android主屏幕所需的时间——然后重新启动它,我会看到匹配ContactsArrayList是[{“12345”}、{“67890”},等等,{“12345”}、{“67890”},等等] 如果我关闭它两次,arraylist会出现三次,以此类推,它会持续变长。它应该只显示每个值一次 我想,editorMatchingContactsArrayList.r

arraylist的格式应为,
[{“12345”},{“67890”},等等..]

但是当我关闭我的应用程序时——我的意思是按后退按钮返回Android主屏幕所需的时间——然后重新启动它,我会看到
匹配ContactsArrayList
[{“12345”}、{“67890”},等等,{“12345”}、{“67890”},等等]

如果我关闭它两次,
arraylist
会出现三次,以此类推,它会持续变长。它应该只显示每个值一次

我想,
editorMatchingContactsArrayList.remove(jsonMatchingContactsArrayList.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();
                }


            }
@覆盖
公共void onResponse(字符串响应){
//将响应JSONArray转换为字符串
字符串匹配ContactsString=response.toString();
//制作一个arraylist,它将保存MatchingContacts字符串的电话号码部分
MatchingContactsArrayList=新建ArrayList();
试一试{
JSONArray对象=新的JSONArray(匹配ContactsAsString);
对于(int x=0;x
SharedReferences.remove()
方法接收用于保存的

在本例中,它是“MatchingContactsAsArrayList”


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

在添加到itI之前,请检查密钥是否存在。我尝试了所有这些操作-清除()、删除(),但没有任何操作。但你是对的——我的回答不正确。对于响应所基于的arraylist,我放置了arraylist.clear(),现在它工作正常。