How to store HashMap on Android?

12,481

Solution 1

SharedPreferences also store data in key-value pair as hashmap, so why not get all key-values from hashmap and store into map, as it:

SharedPreferences pref= getContext().getSharedPreferences("Your_Shared_Prefs"), 
                                                           Context.MODE_PRIVATE);
SharedPreferences.Editor editor= pref.edit();

    for (String s : map.keySet()) {
        editor.putString(s, map.get(s));
    }

To fetch values you can use:

public abstract Map<String, ?> getAll ()

http://developer.android.com/reference/android/content/SharedPreferences.html#getAll%28%29

use:

SharedPreferences pref= getContext().getSharedPreferences("Your_Shared_Prefs"), 
                                                           Context.MODE_PRIVATE);
HashMap<String, String> map= HashMap<String, String> pref.getAll();
for (String s : map.keySet()) {
        String value=map.get(s);
        //Use Value
    }

Code is not compiled, so it may have some minor errors, but should work.

Solution 2

Try this

HashMap<String, String> hashMap = new HashMap<String, String>();
hashMap.put("key", "value");
Intent intent = new Intent(this, MyOtherActivity.class);
intent.putExtra("map", hashMap);
startActivity(intent);

and Another way is HERE

Share:
12,481
Roman
Author by

Roman

I am learning. Right now.

Updated on June 09, 2022

Comments

  • Roman
    Roman about 2 years

    So, I'm trying to store HashMap on Android. I think it's better to use internal storage, but I don't understand how to save HashMap in it and then read it later. Can someone explain how to do that properly, please?

    There are counters with their own names and values. I want to load them onсe when some activity was started, work with them (change, delete, add new), and then save that data to use next time. Right now I use HashMap because it's easy to delete/add values.

    HashMap<String, Integer> counters;