SharedPrefrence保存Map基本方法
1.set
public static void setMapToSharedpreference(Context context, String key, Map<String,Boolean> map ){
SharedPreferences sha= context.getSharedPreferences(SP_NAME,Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sha.edit();
String json = new Gson().toJson(map);
editor.putString(key,json);
editor.commit();
}
2.get
public static Map<String,Boolean> getMapToSharedpreference(Context context, String key){
SharedPreferences sp= context.getSharedPreferences(SP_NAME,Context.MODE_PRIVATE);
Gson gson = new Gson();
String json = sp.getString(key, "");
if(TextUtils.isEmpty(json)){
return null;
}
return gson.fromJson(json, Map.class);
}
3.remove
public static void removeFromSharedPreference(Context context,String key){
SharedPreferences sha= context.getSharedPreferences(SP_NAME,Context.MODE_PRIVATE);
sha.edit().remove(key).commit();
}
注:记得commit否则移除无效