I have a hash map table as below,
HashMap backUpCurency_values = new HashMap();
and i want to
There are a few different ways to approach this. With nothing more to go on than the info that you want to store a HashMap to SharedPreferences, I can only make assumptions.
First thing I'd ask is whether you will be storing other things in the SharedPreferences as well- I'll assume you will.
Here is how I would approach it:
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
SharedPreferences.Editor editor = prefs.edit();
editor.putString("backUpCurency", stringify(backUpCurency_values));
editor.commit();
You may want to see what stringify does:
// turns a HashMap into "key=value|key=value|key=value"
private String stringify(HashMap map) {
StringBuilder sb = new StringBuilder();
for (String key : map.keySet()) {
sb.append(key).append("=").append(map.get(key)).append("|");
}
return sb.substring(0, sb.length() - 1); // this may be -2, but write a unit test
}
Then you can just parse that string with known structure upon reading the shared preferences later.
private HashMap restoreIt() {
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
String backup = settings.getString("backUpCurency", "");
HashMap map = new HashMap();
for (String pairs : backup.split("|")) {
String[] indiv = pairs.split("=");
map.put(indiv[0], indiv[1]);
}
return map;
}