首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如果arraylist为空,我如何保存到shredpreferences?

如果arraylist为空,我如何保存到shredpreferences?
EN

Stack Overflow用户
提问于 2019-03-11 06:37:45
回答 1查看 43关注 0票数 0

每次我的安卓应用程序启动时,我都会从我的服务器上收到一个arraylistMatchingArrayList

代码语言:javascript
运行
复制
        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]

然后我将arraylist保存到sharedpreferences,如下所示:

代码语言:javascript
运行
复制
            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();

因此,下次使用该应用程序时,如果MatchingArrayList已更改为[+111, +222, +333],则它将覆盖上次使用的[+111, +222]arraylist

它工作得很好,除非MatchingArrayListnull或为空。sharedpreferences不会更新。我试过了:

代码语言:javascript
运行
复制
          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?
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2019-03-11 07:34:21

我没有查看我的java arraylist,而是在应用程序的php端检查了我的response是否为空。如下所示:

代码语言:javascript
运行
复制
          if (response.isEmpty()) {

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

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

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/55093105

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档