每次我的安卓应用程序启动时,我都会从我的服务器上收到一个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]
,则它将覆盖上次使用的[+111, +222]
的arraylist
它工作得很好,除非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?
发布于 2019-03-10 23:34:21
我没有查看我的java arraylist
,而是在应用程序的php
端检查了我的response
是否为空。如下所示:
if (response.isEmpty()) {
SharedPreferences sharedPreferencesMatchingContactsAsArrayList = PreferenceManager.getDefaultSharedPreferences(getApplication());
SharedPreferences.Editor editorMatchingContactsAsArrayList = sharedPreferencesMatchingContactsAsArrayList.edit();
editorMatchingContactsAsArrayList.putString("MatchingContactsAsArrayList", "");
editorMatchingContactsAsArrayList.commit();
} else {
这解决了我的问题,更新了sharedpreferences
。
https://stackoverflow.com/questions/55093105
复制相似问题