How to Store Hashmap to android so that it will be reuse when application restart using shared preferences?

后端 未结 5 1937
余生分开走
余生分开走 2020-12-30 06:38

I want to store hashmap to my android application that when restart ,it shows last saved values of hashmap.

HashMap HtKpi=new HashMap&l         


        
5条回答
  •  有刺的猬
    2020-12-30 07:15

    You could serialize it to json and store the resulting string in the preferences. Then when application restarts get the string from preferences and deserialize it.

    EDIT :

    To do so you can use Google Gson for example.

    You will need to wrap your map in a class:

    public class MapWrapper {
      private HashMap myMap;
      // getter and setter for 'myMap'
    }
    

    To store the map:

    Gson gson = new Gson();
    MapWrapper wrapper = new MapWrapper();
    wrapper.setMyMap(HtKpi);
    String serializedMap = gson.toJson(wrapper);
    // add 'serializedMap' to preferences
    

    To retrieve the map:

    String wrapperStr = preferences.getString(yourKey);
    MapWrapper wrapper = gson.fromJson(wrapperStr, MapWrapper.class);
    HashMap HtKpi = wrapper.getMyMap(); 
    

提交回复
热议问题