jobin
jobin

Reputation: 1527

android saving hashmap to SharedPreferences

The RecyclerView in activity_main has three check boxes and at the bottom of activity_main is a button which when clicked saves the checkbox status(true or false) and its adapter position to hashmap. Position is the key and status is the value.Both are converted to String.I want to save it to sharedpreferences.I found that primitive data types can be saved to shared preferences.Is there a way to save hashmap to it.

RecyclerAdapter.java:

public class RecyclerHolder extends RecyclerView.ViewHolder {
    AnimCheckBox checkBox;
    checkBox = (AnimCheckBox) itemView.findViewById(R.id.checkBox);
    checkBox.setChecked(false);
    public RecyclerHolder(final View itemView) {
        super(itemView);
        checkBox.setOnCheckedChangeListener(new AnimCheckBox.OnCheckedChangeListener() {
            @Override
            public void onChange(boolean checked) {
                checkboxclick = true;
                if (checkBox.isChecked()) {
                    boolean check = true;
                    clicked_position = getAdapterPosition();
                    String position = Integer.toString(clicked_position);
                    String check_status = Boolean.toString(check);
                    hashMap.put(position, check_status);
                } else {
                    String removekey = String.valueOf(getAdapterPosition());
                    if (hashMap.containsKey(removekey)) {
                        hashMap.remove(removekey);
                    }
                }
            }
        });

        SharedPreferences sharedPreferences = context.getSharedPreferences("Main", Context.MODE_PRIVATE);
        bt_click_status = sharedPreferences.getBoolean("BtnCheck", false);

        if (hashMap != null && bt_click_status == true) {

            if (checkboxclick == true) {
                SharedPreferences sharedPreferences1 = context.getSharedPreferences("ck_itm", Context.MODE_PRIVATE);
                SharedPreferences.Editor editor = sharedPreferences1.edit();
                editor.put
            }
        }
    }
}

RecyclerAdapter(Edited).java:

GsonBuilder builder = new GsonBuilder();
Gson gson = builder.enableComplexMapKeySerialization().setPrettyPrinting().create();
Type type = new TypeToken < HashMap < String, String >> () {}.getType();
String json = gson.toJson(hashMap, type);
SharedPreferences sharedPreferences1 = context.getSharedPreferences("Ctk", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences1.edit();
editor.putString("chk", json);
editor.commit();

MainActivity.java:

SharedPreferences sharedPreferences1 = getApplicationContext().getSharedPreferences("Ctk", Context.MODE_PRIVATE);
String get = sharedPreferences1.getString("chk", null);
places = new Gson().fromJson(get, new TypeToken < HashMap < String, String >> () {}.getType());
s = places.keySet();
Iterator i = s.iterator();
while (i.hasNext()) {
    Map.Entry entry = (Map.Entry) i.next();
    Log.e("key:" + entry.getKey(), "value:" + entry.getValue());
}

Error:(Error is at "s=places.entrySet() in MainActivity.java)

03 - 09 12: 51: 53.658 29260 - 29260 / com.example.jobinsabu.destination E / AndroidRuntime:
FATAL EXCEPTION: main
java.lang.NullPointerException
at com.example.jobinsabu.destination.MainActivity$1$1.onClick(MainActivity.java: 173)
at android.view.View.performClick(View.java: 4439)
at android.widget.Button.performClick(Button.java: 148)
at android.view.View$PerformClick.run(View.java: 18395)
at android.os.Handler.handleCallback(Handler.java: 725)
at android.os.Handler.dispatchMessage(Handler.java: 92)
at android.os.Looper.loop(Looper.java: 176)
at android.app.ActivityThread.main(ActivityThread.java: 5302)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java: 511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java: 1102)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java: 869)
at dalvik.system.NativeStart.main(Native Method)

Upvotes: 0

Views: 5746

Answers (2)

Pankaj
Pankaj

Reputation: 8058

You can convert it to JSON string and then save it to shared preference

Use Gson

    // convert map to JSON String
    GsonBuilder builder = new GsonBuilder();
    Gson gson = builder.enableComplexMapKeySerialization().setPrettyPrinting().create();
    Type type = new TypeToken<HashMap<Integer,Boolean>>(){}.getType();
    String json = gson.toJson(hashMap, type);

And to convert it back to hashmap

String jsonString = "JSON string";
HashMap<String,String> hashMap = new Gson().fromJson(jsonString, new TypeToken<HashMap<String, String>>(){}.getType());

Upvotes: 8

Bajirao Shinde
Bajirao Shinde

Reputation: 1354

You Can Do That This Bellow Way

Map<String, String> aMap = new HashMap<String, String>();
aMap.put("key1", "val1");
aMap.put("key2", "val2");
aMap.put("Key3", "val3");

SharedPreferences keyValues = getContext().getSharedPreferences("Your_Shared_Prefs"), Context.MODE_PRIVATE);
SharedPreferences.Editor keyValuesEditor = keyValues.edit();

for (String s : aMap.keySet()) {
    keyValuesEditor.putString(s, aMap.get(s));
}

keyValuesEditor.commit();

Upvotes: 0

Related Questions