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

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

    I have a solution. Same thing i had done in my application where i wanted to store the name of states as key and state abbreviation as value. For that declared an string array in "res/values/string.xml". Here is the code used to declare an array :

     
        yourKey1;yourValue1
        yourKey2;yourValue2
        yourKey3;yourValue3
    
    

    And after this, where you want to instantiate your hashmap, do this :

    HashMap map = new HashMap();
        Resources res = getResources();
    
        String[] stringArray = res.getStringArray(R.array.array_string);
    
        //R.array.array_string is the name of your array declared in string.xml
        if(stringArray == null || stringArray.length == 0) return;
    
        for(String string : stringArray) {
            String[] splittedString = string.split(";");
            if(splittedString.length > 0) {
                String key = splittedString[0];
                String value = splittedString[1];
                map.put(key, value);
            }
        }
    

    Now you have your HaspMap instance ready for use. This is simple way of doing this which i prefer.

提交回复
热议问题