Question

I am trying to save hashmap of arraylist. I am using custom class MailMessage which is itself parcelable. How can I save the Hashmaps? I am saving/restoring map as:

<code>
HashMap<String, ArrayList<MailMessage>> emailsMap = new HashMap<String, ArrayList<MailMessage>>();

@Override
    protected void onSaveInstanceState(Bundle outState) {
        outState.putSerializable("emailsMap", emailsMap);
        super.onSaveInstanceState(outState);
    }

    @Override
    protected void onRestoreInstanceState(Bundle state) {
        // TODO Auto-generated method stub
        super.onRestoreInstanceState(state);
        emailsMap = (HashMap<String, ArrayList<MailMessage>>) state.getSerializable("emailsMap");
    }
</code>

But in restore instance state, i am getting empty map. What can be the issue? I am saving restoring in right way?

No correct solution

OTHER TIPS

you can use shared preference to set and get your hashmap.

 /**
 * This method is used to set shared preferences
 * @param context Application context
 * @param key shared object key
 * @param value shared object value
 */
public static void setPreferences(Context context, String key, Object value) {
    SharedPreferences appSharedPrefs = PreferenceManager
            .getDefaultSharedPreferences(context);
    Editor prefsEditor = appSharedPrefs.edit();
    Gson gson = new Gson();
    String json = gson.toJson(value);
    prefsEditor.putString(key, json);
    prefsEditor.commit();
}

/**
 * This method is used to get shared object
 * @param context Application context
 * @param key shared object key
 * @return return value, for default "" asign.
 */
public static HashMap<String, ArrayList<MailMessage>> getPreferences(Context context, String key,
        Class<HashMap<String, ArrayList<MailMessage>>> clazz) {

    SharedPreferences appSharedPrefs = PreferenceManager
            .getDefaultSharedPreferences(context);

    Gson gson = new Gson();
    String json = appSharedPrefs.getString(key, "");
    if (TextUtils.isEmpty(json)) {
        return null;
    }
    return (HashMap<String, ArrayList<MailMessage>>) gson.fromJson(json, clazz);
}

Make sure when you call getPreference to get hashmap, your key is as same as you had used when you have store your object using setSharedPrefence.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top