3

I have created a HashMap in the following way:

HashMap<Integer, String> buttons = new HashMap<Integer, String>();

I need this to remain in this format, however every answer to this solution I have seen only works for HashMap<String, String>

Thanks

Zyzz
  • 208
  • 1
  • 2
  • 11
  • Possible duplicate of [Saving a hash map into Shared Preferences](http://stackoverflow.com/questions/7944601/saving-a-hash-map-into-shared-preferences) – e4c5 Oct 01 '15 at 22:37

3 Answers3

14

Hey I found a way in the end :)

I just changed the HashMap I had to format and then did the following to save the contents:

SharedPreferences.Editor editor = getSharedPreferences(PREFS_NAME, 0).edit();
for( Entry entry : backUpCurency_values.entrySet() ) 
editor.putString( entry.getKey(), entry.getValue() );
editor.commit();

and the following to retrieve the HashpMap:

SharedPreferences prefs = getSharedPreferences(PREFS_NAME, 0);
for( Entry entry : prefs.getAll().entrySet() )
   backUpCurency_values.put( entry.getKey(), entry.getValue().toString() );
Zied R.
  • 4,964
  • 2
  • 36
  • 67
Zyzz
  • 208
  • 1
  • 2
  • 11
5

There is no support for any HashMap in SharedPreferences. You can treat a whole SharedPreferences as being a bit like a HashMap, but it is not a HashMap, and you cannot store a HashMap in an individual preference.

You are welcome to convert your HashMap into a String that could be stored in a SharedPreferences value, such as by converting it into JSON.

CommonsWare
  • 986,068
  • 189
  • 2,389
  • 2,491
0

Converting it to JSON (as CommonsWare pointed out) is an option. Alternatively, the way I did it (since I'm not familiar with JSON) is to serialize it with Apache's ObjectSerializer class (found here: ObjectSerializer.java).

Simply call the serialize method when you want to store it and deserialize when you want to turn it back into a Map.

Halogen
  • 551
  • 6
  • 11