3

I have a hash map table as below,

HashMap<String, String> backUpCurency_values = new HashMap<String, String>();

and i want to store these value for future use.. how can i do that?

Edit:
i will store to Country names and currencyvalue as key and value pair...

vnshetty
  • 20,051
  • 23
  • 64
  • 102

5 Answers5

6

You should just use a for-each loop and iterate through the map like this:

SharedPreferences.Editor editor = getSharedPreferences(PREFS_NAME, 0).edit();

for( Entry<String, String> entry : backUpCurency_values.entrySet() ) 
  editor.putString( entry.getKey(), entry.getValue() );

editor.commit();

Then when you need to get your values back for later use you do the following (provided that this SharedPreference-object is reserved for currency):

SharedPreferences prefs = getSharedPreferences(PREFS_NAME, 0);

for( Entry<String, ?> entry : prefs.getAll().entrySet() ) 
  backUpCurency_values.put( entry.getKey(), entry.getValue().toString() );
kaspermoerch
  • 16,127
  • 4
  • 44
  • 67
  • It looks handy.. but i got " Can only iterate over an array or an instance of java.lang.Iterable" synax error – vnshetty Nov 16 '11 at 12:39
  • It is. And provided you only save currencies into this SharedPreferences object (or have one dedicated to that purpose) you can get them all back with the `getAll()` method of `SharedPreferences` which will provide you with a `Map`. – kaspermoerch Nov 16 '11 at 12:43
  • My bad - you need to call the method `entrySet()` on your `HashMap`. I edited above to show the correct syntax. – kaspermoerch Nov 16 '11 at 12:46
1

You can use SharedPreferences.

settings = getSharedPreferences(PREFS_NAME, 0);
SharedPreferences.Editor editor = settings.edit();

//The below step you can repeat to put all the key value pair from the hashmap to the shared preference

editor.putString("Key", Value);

// Commit the edits!
editor.commit();

And to retrieve later use

SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
boolean silent = settings.getString(<Key>, <defaultvalue>);
Sush
  • 6,839
  • 1
  • 18
  • 26
1

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<String, String> into "key=value|key=value|key=value"
   private String stringify(HashMap<String, String> 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<String, String> restoreIt() {
      SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
      String backup = settings.getString("backUpCurency", "");
      HashMap<String, String> map = new HashMap<String, String>();
      for (String pairs : backup.split("|")) {
         String[] indiv = pairs.split("=");
         map.put(indiv[0], indiv[1]);
      }
      return map;
   }
Travis
  • 3,737
  • 1
  • 24
  • 24
0

You can use SharedPreference like this:

SharedPreferences s_pref=PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
Editor edit=s_pref.edit();

edit.putString("key","value");
edit.commit();

later you can use it like:

String s=s_pref.getString("key","default value");

But,you must have list of keys you have saved values with,into SharedPreferences so that you can get values easily at the time of retrieving them.

Hiral Vadodaria
  • 19,158
  • 5
  • 39
  • 56
0

To store the values use this code

SharedPreferences preferences = getSharedPreferences(
            PREF_FILE_NAME, MODE_PRIVATE);
    if (value.equals("")) {

        boolean storedPreference = preferences.contains(key);
        if (storedPreference) {
            SharedPreferences.Editor editor = preferences.edit();
            editor.remove(key); // value to store
            Log.d("KEY",key);
            editor.commit();
        }
    }else{

        SharedPreferences.Editor editor = preferences.edit();
        editor.putString(key, value); // value to store
        Log.d("KEY",key);
        editor.commit();
    }

To retrieve the values use this code

SharedPreferences preferences = getSharedPreferences(
            PREF_FILE_NAME, MODE_PRIVATE);
    Map<String, String> map = (Map<String, String>) preferences.getAll();
    if(!map.isEmpty()){
        Iterator<Entry<String, String>> iterator = map.entrySet().iterator();
        while(iterator.hasNext()){
             Map.Entry pairs = (Map.Entry)iterator.next();
                pairs.getKey()+pairs.getValue();
                      //write code here
        }
    }
Balaji.K
  • 8,745
  • 5
  • 30
  • 39
  • the code i already tried from here.. http://stackoverflow.com/questions/4953466/how-to-store-hashmap-so-that-it-can-be-retained-it-value-after-a-device-reboot But n0t really wrked for me... – vnshetty Nov 16 '11 at 12:37
  • It's working for me.will you paste your code,so that we will rectify the error. – Balaji.K Nov 16 '11 at 13:01