代码之家  ›  专栏  ›  技术社区  ›  CHarris

如果arraylist为空,如何保存到shredReferences?

  •  0
  • CHarris  · 技术社区  · 5 年前

    arraylist , MatchingArrayList ,从我的服务器:

            try {
              JSONArray Object = new JSONArray(MatchingAsString);
              //for every object in the Array
              for (int x = 0; x < Object.length(); x++) {
                final JSONObject obj = Object.getJSONObject(x);
                MatchingArrayList.add(obj.getString("usernameMatch"));
                }
    

    [+111, +222]

    数组表 sharedpreferences

                SharedPreferences sharedPreferencesMAL = PreferenceManager.getDefaultSharedPreferences(getApplication());
                SharedPreferences.Editor editorMAL = sharedPreferencesMAL.edit();
                Gson gsonMAL = new Gson();
                String jsonMAL = gsonMAL.toJson(MatchingArrayList);
                editorMAL.putString("MatchingArrayList", jsonMAL);
                editorMAL.commit();
    

    所以下一次使用应用程序时,如果 匹配ArrayList [+111, +222, +333] ,例如,它将覆盖上次使用的 数组表 属于 [+111, +222]

    匹配ArrayList null 或者是空的。这个 不更新。我试过:

              if (MatchingArrayList == null) {
    
                SharedPreferences sharedPreferencesMAL = PreferenceManager.getDefaultSharedPreferences(getApplication());
                SharedPreferences.Editor editorMAL = sharedPreferencesMAL.edit();
                editorMAL.putString("MatchingArrayList", null);
                editorMAL.commit();
              } else {
    
                //save MatchingArrayList into sharedpreferences so we can use it elsewhere
                SharedPreferences sharedPreferencesMAL = PreferenceManager.getDefaultSharedPreferences(getApplication());
                SharedPreferences.Editor editorMAL = sharedPreferencesMAL.edit();
                Gson gsonMAL = new Gson();
                String jsonMAL = gsonMAL.toJson(MatchingArrayList);
                editorMAL.putString("MatchingArrayList", jsonMAL);
                editorMAL.commit();
    
              }
    
      But still the last arraylist is being used. How can I fix this?
    
    0 回复  |  直到 5 年前
        1
  •  0
  •   CHarris    5 年前

    而不是看我的java arraylist response php 我的应用程序的侧面。这样地:

              if (response.isEmpty()) {
    
                SharedPreferences sharedPreferencesMatchingContactsAsArrayList = PreferenceManager.getDefaultSharedPreferences(getApplication());
                SharedPreferences.Editor editorMatchingContactsAsArrayList = sharedPreferencesMatchingContactsAsArrayList.edit();
                editorMatchingContactsAsArrayList.putString("MatchingContactsAsArrayList", "");
                editorMatchingContactsAsArrayList.commit();
              } else {
    

    解决了我的问题,更新了 sharedpreferences .