[英]How to save hashmap to shared preference?
I want to save a hashmap to shared preference .我想将哈希图保存到共享首选项。 The keys of hashmap will be ipaddresses and values will be flags(like true or false).
hashmap 的键将是 ipaddresses,值将是标志(如 true 或 false)。 To display the ipaddreeses to user I have to get all the keys of hashmap.
要向用户显示 ipaddrees,我必须获取 hashmap 的所有键。 And whenever i want to display the flag value i have to get it using ipaddress key.I do not want to use a separate shared preferences or file for this.
每当我想显示标志值时,我都必须使用 ipaddress 键来获取它。我不想为此使用单独的共享首选项或文件。 How can i do this?
我怎样才能做到这一点?
Try this to save objects in SharedPreferences.试试这个以在 SharedPreferences 中保存对象。
you need to add Gson library to your project.您需要将 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;
}
You can save it as an object or convert it to JSON and save it:您可以将其另存为对象或将其转换为 JSON 并保存:
store and retrieve a class object in shared preference 在共享首选项中存储和检索类对象
This might be helpful also:这也可能有帮助:
How Android SharedPreferences save/store object Android SharedPreferences 如何保存/存储对象
It explains how to convert an object to JSON that you can save with SharedPreferences
and retrieve/rebuild.它解释了如何将对象转换为可以使用
SharedPreferences
保存并检索/重建的 JSON。
with Kotlin it would be like this:使用 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
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.