Amritesh Singh
Amritesh Singh

Reputation: 13

How to store and retrive HashMap<Integer, boolean[]> hashMapB=new HashMap<Integer,boolean[]>() into shared preferences in android

I want to create Expandable List view for filter and i am storing check box status of every group into HashMap .but after apply filter first time and again going for the filter i am not able to retain state of check box.I want to store it into shared preference . can any one suggest how to do it.

Upvotes: 1

Views: 591

Answers (1)

Mukeshkumar S
Mukeshkumar S

Reputation: 795

Inserting Into Shared Pref,

 HashMap<Integer, boolean[]> hashmapB = new Hashmap<>;

After Adding Values to Hashmap then convert it JSON

JSONObject jsonObject = new JSONObject(hashmapB);
String jsonString = jsonObject.toString();

SharedPreferences keyValues = getSharedPreferences("Your_Shared_Prefs"), Context.MODE_PRIVATE);
SharedPreferences.Editor editor = keyValues.edit();
editor.putString("hashmapB_key",jsonString);

Retrieve From Pref,

String hashmapB_String = Sellerregistration_Pref.getString("hashmapB_key",
                (new JSONObject()).toString());

String To Hashmap (Here You Might Get Problem I just did this based on assumption),

HashMap<Integer,boolean[]>hashmapB_Ret = new HashMap<>();

try {
    JSONObject jsonObject = new JSONObject(hashmapB_String);
    Iterator<String> keysItr = jsonObject.keys();
    while(keysItr.hasNext()) {
          String key = keysItr.next();
          boolean[] values = (boolean[]) jsonObject.get(key);
          hashmapB_Ret.put(Integer.valueOf(key), value);
    }
 } catch (JSONException e) {
        e.printStackTrace();
 }

Upvotes: 1

Related Questions