0

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();

                        }
jobin
  • 1,489
  • 5
  • 27
  • 52

2 Answers2

2

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

Community
  • 1
  • 1
amukhachov
  • 5,822
  • 1
  • 41
  • 60
  • I checked the link.It is said the key and value must be string.But the key is Integer object and value is Boolean in my Hashmap – jobin Mar 02 '16 at 08:53
0
    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

Community
  • 1
  • 1
배준모
  • 591
  • 5
  • 12