As a spin off of Vinoj John Hosan's answer, I modified the answer to allow for more generic insertions, based on the key of the data, instead of a single key like "My_map".
In my implementation, MyApp is my Application override class, and MyApp.getInstance() acts to return the context.
public static final String USERDATA = "MyVariables";
private static void saveMap(String key, Map<String,String> inputMap){
SharedPreferences pSharedPref = MyApp.getInstance().getSharedPreferences(USERDATA, Context.MODE_PRIVATE);
if (pSharedPref != null){
JSONObject jsonObject = new JSONObject(inputMap);
String jsonString = jsonObject.toString();
SharedPreferences.Editor editor = pSharedPref.edit();
editor.remove(key).commit();
editor.putString(key, jsonString);
editor.commit();
}
}
private static Map<String,String> loadMap(String key){
Map<String,String> outputMap = new HashMap<String,String>();
SharedPreferences pSharedPref = MyApp.getInstance().getSharedPreferences(USERDATA, Context.MODE_PRIVATE);
try{
if (pSharedPref != null){
String jsonString = pSharedPref.getString(key, (new JSONObject()).toString());
JSONObject jsonObject = new JSONObject(jsonString);
Iterator<String> keysItr = jsonObject.keys();
while(keysItr.hasNext()) {
String k = keysItr.next();
String v = (String) jsonObject.get(k);
outputMap.put(k,v);
}
}
}catch(Exception e){
e.printStackTrace();
}
return outputMap;
}
added in API level 1 Map getAll () Retrieve all values from
the preferences.
Note that you must not modify the collection returned by this method,
or alter any of its contents. The consistency of your stored data is
not guaranteed if you do.
Returns Map Returns a map containing a list of pairs
key/value representing the preferences.
The lazy way: storing each key directly in SharedPreferences
For the narrow use case when your map is only gonna have no more than a few dozen elements you can take advantage of the fact that SharedPreferences works pretty much like a map and simply store each entry under its own key:
Storing the map
Map<String, String> map = new HashMap<String, String>();
map.put("color", "red");
map.put("type", "fruit");
map.put("name", "Dinsdale");
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
// OR use a specific pref name
// context.getSharedPreferences("myMegaMap");
for (Map.Entry<String, String> entry : map.entrySet()) {
prefs.edit().putString(entry.getKey(), entry.getValue());
}
Reading keys from the map
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
// OR use a specific pref name
// context.getSharedPreferences("myMegaMap");
prefs.getString("color", "pampa");
In case where you use a custom preference name (i.e. context.getSharedPreferences("myMegaMap")) you can also get all keys with prefs.getAll()
Your values can be of any type supported by SharedPreferences: String, int, long, float, boolean.
SharedPreferences sharedpreferences = getSharedPreferences(MyPREFERENCES,Context.MODE_PRIVATE);
Editor editor = sharedpreferences.edit();
editor.putStringSet("key", hashmapobj );
editor.apply(); //Note: use commit if u wan to receive response from shp
3) Reading data like :-
in a new class where you want it to be read
HashMap hashmapobj_RECIVE = new HashMap();
SharedPreferences sharedPreferences (MyPREFERENCES,Context.MODE_PRIVATE;
//reading HashMap from sharedPreferences to new empty HashMap object
hashmapobj_RECIVE = sharedpreferences.getStringSet("key", null);
You don't need to save HashMap to file as someone else suggested. It's very well easy to save a HashMap and to SharedPreference and load it from SharedPreference when needed. Here is how:
Assuming you have a
class T
and your hash map is:
HashMap<String, T>
which is saved after being converted to string like this:
The following code will read the hash map from saved shared preference and correctly load back into mUsageStatsMap:
Gson gson = new Gson();
String json = sharedPref.getString("MyHashMap", "");
Type typeMyType = new TypeToken<HashMap<String, UsageStats>>(){}.getType();
HashMap<String, UsageStats> usageStatsMap = gson.fromJson(json, typeMyType);
mUsageStatsMap = usageStatsMap;
The key is in Type typeMyType which is used in * gson.fromJson(json, typeMyType)* call. It made it possible to load the hash map instance correctly in Java.