问题遇到的现象和发生背景
使用sharedpreferences全局存储map将map转成json字符串进行存储,在清空时使用putString方法将值设置成空字符串,但是在获取时,还是之前的值 并没有为空字符串。
问题相关代码,请勿粘贴截图
private SharedPreferences share;
private SharedPreferences.Editor editor;
private Map<String,String> moreData = new HashMap<>();
private SharedPreferencesUtils() {
share = EallApplication.getContext().getSharedPreferences(SHARED_NAME, Context.MODE_PRIVATE);
editor = share.edit();
}
/**
* 单例模式
*/
private static SharedPreferencesUtils instance;//单例模式 双重检查锁定
public static SharedPreferencesUtils getInstance() {
if (instance == null) {
synchronized (SharedPreferencesUtils.class) {
if (instance == null) {
instance = new SharedPreferencesUtils();
}
}
}
return instance;
}
/**
* 用于保存集合
*
* @param key key
* @param map map数据
* @return 保存结果
*/
public void putHashMapData(String key, Map<String, String> map) {
if (map == null){
moreData.clear();
editor.putString(key, "");
editor.apply();
return;
}
moreData.putAll(map);
try {
Gson gson = new Gson();
String json = gson.toJson(moreData);
editor.putString(key, json);
} catch (Exception e) {
e.printStackTrace();
}
editor.apply();
return;
}
public Map<String, String> getHashMapData(String key) {
String json = share.getString(key, "");
Map<String,String> map = new Gson().fromJson(json, new TypeToken<HashMap<String,Object>>(){}.getType());
return map;
}