我想将 hashmap 保存到共享偏好。 hashmap的键将是ipaddresses,值将是标志(如true或false)。要向用户显示ipaddreeses,我必须获取hashmap的所有键。每当我想显示标志值时,我必须使用ipaddress key获取它。我不想为此使用单独的共享首选项或文件。我怎么能这样做?
答案 0 :(得分:1)
尝试此操作以在SharedPreferences中保存对象。
您需要将Gson库添加到项目中。
public void putMyObject(String key , Object obj) {
//AnyVehicleModel mvehicle =new AnyVehicleModel();
SharedPreferences.Editor editor = preferences.edit();
Gson gson = new Gson();
String json = gson.toJson(obj);
editor.putString(key,json);
editor.apply();
}
public MyObject getMyObject(String key) {
Gson gson = new Gson();
String json = preferences.getString(key,"");
MyObject obj = gson.fromJson(json, MyObject.class);
if (obj== null){return new MyObject ();}
return obj;
}
答案 1 :(得分:0)
您可以将其另存为对象或将其转换为JSON并保存:
store and retrieve a class object in shared preference
这也可能有用:
How Android SharedPreferences save/store object
它解释了如何将对象转换为可以使用SharedPreferences
保存并检索/重建的JSON。
答案 2 :(得分:0)
使用Kotlin会是这样:
fun saveUserInfoMap(userInfo: HashMap<String, Any>){
val prefs = PreferenceManager
.getDefaultSharedPreferences(App.appContext)
val gson = Gson()
val editor = prefs.edit()
val json = gson.toJson(userInfo)
editor.putString("user_info", json)
editor.apply()
}
@Suppress("UNCHECKED_CAST")
fun getUserInfoMap(): HashMap<String, Any>? {
val prefs = PreferenceManager
.getDefaultSharedPreferences(App.appContext)
val gson = Gson()
val json = prefs.getString("user_info", "")
val typeToken = object: TypeToken<HashMap<String, Any>>(){}
var obj: HashMap<String, Any> = HashMap()
if (!TextUtils.isEmpty(json)) {
obj = gson.fromJson<Any>(json, typeToken.type) as HashMap<String, Any>
}
return obj
}