Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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).

like image 275
Lata Avatar asked Aug 13 '12 09:08

Lata


People also ask

Can I store HashMap in Sharedpreferences Android?

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.

How does the HashMap class store the data in Android?

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.

How can use HashMap in Android example?

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.

What is the use of HashMap in Android?

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.


1 Answers

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(); 
like image 75
kgautron Avatar answered Sep 22 '22 03:09

kgautron