how to store and retrieve (key,value) kind of data using saved preferences android

后端 未结 5 1853
终归单人心
终归单人心 2021-01-06 18:10

I have a hash map table as below,

HashMap backUpCurency_values = new HashMap();

and i want to

5条回答
  •  失恋的感觉
    2021-01-06 18:40

    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;
       }
    

提交回复
热议问题