14

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

Nandkumar Tekale
  • 16,024
  • 8
  • 58
  • 85
Lata
  • 161
  • 2
  • 3
  • 10
  • 3
    what if in future you will have more than just these 44 rows? why not to use a sqlite? just a thought. other than that you can check this link http://stackoverflow.com/questions/8151523/how-to-store-and-retrieve-key-value-kind-of-data-using-saved-preferences-andro and another article on json serialization in android http://blogs.msdn.com/b/dimast/archive/2011/07/04/serializing-de-serializing-object-to-from-json-string-on-android-os.aspx – Sergey Benner Aug 13 '12 at 09:53
  • i have fix 44 values ..in that 11 rows and 4 columns ..i want to show that values to table layout later. – Lata Aug 13 '12 at 10:08

5 Answers5

24

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(); 
kgautron
  • 7,915
  • 9
  • 39
  • 60
  • Is your comment a request for help? – kgautron Aug 13 '12 at 10:30
  • ya..i want more help for solving this issue – Lata Aug 13 '12 at 10:40
  • And how do you expect to get help without telling the problem you are running into? – kgautron Aug 13 '12 at 11:16
  • Sorry.. plz help me for hashtable storing... i want to store hash table store anyways..... and want to show it in table layout.. for that may be (1)storing hashtable and again transfer it in hashtable for showing it in table layout..somewhat like this i m thinking.. – Lata Aug 13 '12 at 11:27
  • @KayKay can you plz tell what logic goes into getMyMap() method, is it simple getter-setter or anything else have to take case of? – Shirish Herwade Jun 02 '14 at 12:11
  • @ShiriHrw just a regular getter – kgautron Jun 11 '14 at 09:34
  • i got some problem when i get Hashmap from gson. com.qb.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_OBJECT but was BEGIN_ARRAY at line 1 column 2 – Ram Feb 26 '15 at 10:43
4

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<String, Integer> 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<String, Integer> map= (HashMap<String, Integer>) pref.getAll();
for (String s : map.keySet()) {
        Integer value=map.get(s);
        //Use Value
}
Johny B
  • 944
  • 8
  • 15
Raghav Sood
  • 81,899
  • 22
  • 187
  • 195
4

using Raghav's I created a complete working example:

public class AppCache {
public static HashMap<String, String> hashMap = null;

/* REPOSITORY NAME */
public static final String REPOSITORY_NAME = "HMIAndroid_System_Settings";

/* SETTINGS */
public static final String SETTING_PLANNED = "DATA_PLANNED";
public static final String SETTING_ACTUAL = "DATA_ACTUAL";
public static final String SETTING_ETA = "DATA_ETA";
public static final String SETTING_OR = "DATA_OR";
public static final String SETTING_LINEID = "LINEID";
public static final String SETTING_SERVERIP = "SERVERIP";

public static void LoadSettings(Context context) {
    SharedPreferences pref = context.getSharedPreferences(REPOSITORY_NAME, Context.MODE_PRIVATE);
    hashMap = (HashMap<String, String>) pref.getAll();
    if(hashMap == null) {
        hashMap = new HashMap<String, String>();
    }
}

public static void SaveSettings(Context context) {
    if(hashMap == null) {
        hashMap = new HashMap<String, String>();
    }

    //persist
    SharedPreferences pref = context.getSharedPreferences(REPOSITORY_NAME, Context.MODE_PRIVATE);
    SharedPreferences.Editor editor = pref.edit();
    for (String s : hashMap.keySet()) {
        editor.putString(s, hashMap.get(s));
    }
    editor.commit();
}
}

Then in your onCreate load it:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    //load settings
    AppCache.LoadSettings(getApplicationContext());
    Log.d("onCreate","My LineID=" + AppCache.hashMap.get(AppCache.SETTING_LINEID));
    Log.d("onCreate","Dest ServerIP=" + AppCache.hashMap.get(AppCache.SETTING_SERVERIP));
}

at any time anywhere in your app update settings:

AppCache.hashMap.put(AppCache.SETTING_LINEID, "1");
AppCache.hashMap.put(AppCache.SETTING_SERVERIP, "192.168.1.10");

in your onDestroy save settings to cache:

@Override
protected  void onDestroy() {
    //save settings
    AppCache.SaveSettings(getApplicationContext());
}
JJ_Coder4Hire
  • 4,706
  • 1
  • 37
  • 25
  • I would just call the saving method at "onStop", not "onDestroy". The answers here explain why: http://stackoverflow.com/questions/13956528/save-data-in-activitys-ondestroy-method – Dinidiniz May 04 '16 at 21:10
0
   @Override
protected void onSaveInstanceState(Bundle outState) {
    // TODO Auto-generated method stub
    super.onSaveInstanceState(outState);
}

You can store it here.... This method is called before an activity may be killed so that when it comes back some time in the future it can restore its state.

And then you can retireve it back from here,,,

@Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onRestoreInstanceState(savedInstanceState);
}

This method is called after onStart() when the activity is being re-initialized from a previously saved state, given here in savedInstanceState...

I think that this will help

Rakesh Gondaliya
  • 1,050
  • 3
  • 25
  • 42
0

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 :

 <string-array name="array_string">
    <item>yourKey1;yourValue1</item>
    <item>yourKey2;yourValue2</item>
    <item>yourKey3;yourValue3</item>
</string-array>

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

HashMap<String, String> map = new HashMap<String, String>();
    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.

Suresh
  • 7,785
  • 1
  • 16
  • 28
  • I have hashmap ready..no issue with that.... i only wish it to store because hashmap is volatile for storage. – Lata Aug 13 '12 at 10:09
  • Yes i understood what you want to do. But here what i am doing is storing array and at runtime i am creating instance of hashmap instead of storing it. Anyways it was just what i did, if you find any other solution, please post it here. so that i can also try that. – Suresh Aug 13 '12 at 10:16