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). To display the ipaddreeses to user I have to get all the keys of 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. How can i do this?
Asked
Active
Viewed 4,563 times
0
-
2Possible dublicate of http://stackoverflow.com/questions/7944601/saving-a-hash-map-into-shared-preferences – Anjali Dec 31 '14 at 06:39
-
`I do not want to use a separate shared preferences or file for this.` Why? Do you have anther entries into prefs as well? – Pankaj Kumar Dec 31 '14 at 06:39
-
Yes..i am saving another values to shared preference.that is why i want to save ipaddresses as hashmap. – andro-girl Dec 31 '14 at 06:42
3 Answers
1
Try this to save objects in SharedPreferences.
you need to add Gson library to your project.
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;
}

H4SN
- 1,482
- 3
- 24
- 43
-
See example @https://github.com/pchauhan/StoreandRetrieveObjectClassDemo/blob/master/src/com/pc/demo/GSonDemoActivity.java – H4SN Dec 31 '14 at 07:44
0
You can save it as an object or convert it to JSON and save it:
store and retrieve a class object in shared preference
This might be helpful also:
How Android SharedPreferences save/store object
It explains how to convert an object to JSON that you can save with SharedPreferences
and retrieve/rebuild.
0
with Kotlin it would be like this:
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
}

Hamid Zandi
- 2,714
- 24
- 32