为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

慕婉清6462132 2022-07-27 20:07:53
每次我的 Android 应用程序启动时,我都会从我的服务器获得一个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]然后我像arraylist这样保存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();所以下次使用该应用时,如果MatchingArrayList已更改为[+111, +222, +333],例如,它将覆盖上次使用arraylist的[+111, +222]它运行良好,除非MatchingArrayList是null或为空。sharedpreferences不更新。我试过了:          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?
查看完整描述

1 回答

?
慕运维8079593

TA贡献1876条经验 获得超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.


查看完整回答
反对 回复 2022-07-27
  • 1 回答
  • 0 关注
  • 77 浏览

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号