I want to store hashmap to my android application that when restart ,it shows last saved values of hashmap.
HashMap<Integer,String> HtKpi=new HashMap<Integer,String>();
is my hashmap and 44 values are stored in it dynamically. That works fine!!! now,I want to store it for future use(Application restart or reuse).
This example demonstrates about How can I save a HashMap to Shared Preferences in Android. Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project. Step 2 − Add the following code to res/layout/activity_main. xml.
It stores the data in the pair of Key and Value. HashMap contains an array of the nodes, and the node is represented as a class. It uses an array and LinkedList data structure internally for storing Key and Value.
Description: In Step 1, we have created an object of HashMap collection. In Step 2, we have used put method to add key value pair in the data structure that we have created in step 1. In Step 3, we have used for each loop to retrieve the values from the HashMap object.
A HashMap is a structure allowing one to store (key,value) items. A hash function pairs each key to an array index where the value will be stored.
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<Integer, String> 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<Integer, String> HtKpi = wrapper.getMyMap();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With