android将hashmap保存到SharedPreferences中 [英] android saving hashmap to SharedPreferences

查看:1322
本文介绍了android将hashmap保存到SharedPreferences中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

activity_main 中的 RecyclerView 有三个复选框, activity_main 底部是一个按钮,点击将复选框状态( true false )及其适配器位置保存为 code>。位置是关键,状态是值。它们都转换为字符串。我想将它保存到 sharedpreferences 。我发现原始数据类型可以保存为共享首选项。是否有一种方法可以将 hashmap 保存到它。

RecyclerAdapter.java

 公共类RecyclerHolder扩展RecyclerView.ViewHolder {
AnimCheckBox checkBox;
checkBox =(AnimCheckBox)itemView.findViewById(R.id.checkBox);
checkBox.setChecked(false);
public RecyclerHolder(final查看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);

如果(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(已编辑).java:

  GsonBuilder builder = new GsonBuilder(); 
Gson gson = builder.enableComplexMapKeySerialization()。setPrettyPrinting()。create();
键入type = new TypeToken< HashMap<字符串,字符串>> (){} .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());
}

错误:(错误位于MainActivity的s = places.entrySet() .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。循环(Looper.java:176)
在android.app.ActivityThread.main(ActivityThread.java:5302)
在java.lang.reflect.Method.invokeNative(本地方法)
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)


解决方案

您可以将其转换为 JSON 字符串,然后将其保存到共享首选项



使用 Gson

  //将地图转换为JSON字符串
GsonBuilder builder = new GsonBuilder();
Gson gson = builder.enableComplexMapKeySerialization()。setPrettyPrinting()。create();
Type type = new TypeToken< HashMap< String,String>(){}。getType();
String json = gson.toJson(hashMap,type);

然后将其转换为 hashmap

 字符串jsonString =JSON string; 
HashMap< String,String> hashMap = new Gson()。fromJson(jsonString,new TypeToken< HashMap< String,String>>(){}。getType());


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)

解决方案

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<String,String>(){}.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());

这篇关于android将hashmap保存到SharedPreferences中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆