jobin
jobin

Reputation: 1527

Android save hashmap to SharedPreferences

I have a Recyclerview which has checkboxes which when clicked saves the status of checkboxes and their position in the Recyclerview layout in the hashmap.I want to send the hashmap to another activity.Is it possible to save hashmap to SharedPreferences.

Code:

if(checkBox.isChecked()){
                        boolean check=true;
                        clicked_position=getAdapterPosition();
                        i=new Integer(clicked_position);
                       hashMap.put(i, check);}
 if(hashMap!=null){
                            SharedPreferences selectedplaces=context.getSharedPreferences("selectedplaces",Context.MODE_PRIVATE);
                            SharedPreferences.Editor editor=selectedplaces.edit();

                        }

Upvotes: 0

Views: 1411

Answers (2)

amukhachov
amukhachov

Reputation: 5900

You can convert your map to JSON and read it back from String when necessary.

Here is how to convert it to JSON: How to convert HashMap to json Array in android?

And here is how to parse it back to HashMap: Convert a JSON String to a HashMap

[EDIT] If keys are not of String format this as well can be easily achieved with GSON library:

        Map<Integer, Boolean> oldMap = new HashMap<>();
        oldMap.put(1, true);
        oldMap.put(2, false);

        Type typeOfHashMap = new TypeToken<Map<Integer, Boolean>>() { }.getType();
        Gson gson = new GsonBuilder().create();
        String json = gson.toJson(oldMap, typeOfHashMap);
        System.out.println(json);
        Map<Integer, Boolean> newMap = gson.fromJson(json, typeOfHashMap);
        System.out.println(newMap.get(1));
        System.out.println(newMap.get(2));

Just add compile 'com.google.code.gson:gson:2.4' to your build.gradle

Upvotes: 2

배준모
배준모

Reputation: 601

    if(checkBox.isChecked()){
                            boolean check=true;
                            clicked_position=getAdapterPosition();
                            i=new Integer(clicked_position);
                           hashMap.put(i, check);}
     if(hashMap!=null){
                                SharedPreferences selectedplaces=context.getSharedPreferences("selectedplaces",Context.MODE_PRIVATE);
                                SharedPreferences.Editor editor=selectedplaces.edit();
                                editor.put("key",hashMap.toString());
                                editor.commit;
                            }

and finally you can convert your SharePreferences to HashMap. String to HashMap JAVA

Upvotes: 0

Related Questions