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

后端 未结 5 1968
余生分开走
余生分开走 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:00

    Serialize it and save it in shared preferences or in a file. Whether you can do this, of course, depends on the data types being mapped from and to. (This won't work, for instance, if you try to serialize a View.)

    Example:

    //persist
    HashMap counters; //the hashmap you want to save
    SharedPreferences pref = getContext().getSharedPreferences("Your_Shared_Prefs", Context.MODE_PRIVATE);
    SharedPreferences.Editor editor = pref.edit();    
    for (String s : counters.keySet()) {
        editor.putInteger(s, counters.get(s));
    }
    editor.commit();
    
    
    //load
    SharedPreferences pref = getContext().getSharedPreferences("Your_Shared_Prefs", Context.MODE_PRIVATE);
    HashMap map= (HashMap) pref.getAll();
    for (String s : map.keySet()) {
            Integer value=map.get(s);
            //Use Value
    }
    

提交回复
热议问题