3

I want to store some data like key and value pair in internal storage. so i am using HashMap to store key,value pair .but i don'get sufficient solution to store and retrieve this HashMap into sharedpreferences. Please give me some solution.

i am put my code below:

HashMap<String, String> MapListMesasges = new HashMap<String, String>();
MapListMesasges.put(FromName, message.getBody());
preferences = mActivity.getSharedPreferences(
                                SharePreference_messages_history_name,
                                Context.MODE_PRIVATE);
                        SharedPreferences.Editor editor = preferences.edit();
                        for (Entry<String, String> entry : MapListMesasges
                                .entrySet()) {
                            editor.putString(entry.getKey(), entry.getValue());
                        }
                        editor.commit();

and retrieve data from Sharedprefernces:

preferences = mActivity.getSharedPreferences(
                SharePreference_messages_history_name, Context.MODE_PRIVATE);
        for (Entry<String, ?> entry : preferences.getAll().entrySet()) {
            MapListMesasges.put(entry.getKey(), entry.getValue().toString());
        }

i will also store hashmap in adapter and set into listview. My main purpose is to store and retrieve data into sharedprefernces and also show data into listview.

Thanks in advance.

dipali
  • 10,966
  • 5
  • 25
  • 51

3 Answers3

0

The easiest way to store HashMap in Preferences is just convert it to the string and store it.

On the Otherside get that string convert it in HashMap and enjoy.

To Convert String to HashMap & vice-versa check this link.

Community
  • 1
  • 1
Dhrumil Shah - dhuma1981
  • 15,166
  • 6
  • 31
  • 39
0

You can use json for solution.

For example:

**JSON**

    {
     [
      "name1","message1",
      "name2","message2"
     ]
    }

Store this entire json string with some key and use same key to retrieve. Just you need to parse/create JSON. You can use GSON lib for JSON creation/parsing

Pratik Popat
  • 2,891
  • 20
  • 31
0

There's special thing for doing operations like you described and this is SQLite. But if you really want to store them in SharedPreferences, you can do it. Your solution almost work. You just need to store keys as well.

StringBuilder b = new StringBuilder();
for (Entry<String, String> entry : MapListMesasges.entrySet()) {
      editor.putString(entry.getKey(), entry.getValue());
      if(b.length() != 0){
           b.append(",");
      }
      b.append(entry.getKey());
 }
editor.putString("KEY_FOR_PREF_KEYS",b.toString());

And to retrieve data use this

String[] keys = preferences.getString("KEY_FOR_PREF_KEYS","").split(",");
for (int i = 0; i < keys.length; i++) {
    MapListMesasges.put(keys[i], preferences.getString(keys[i]));
}
dooplaye
  • 999
  • 13
  • 28