Android SharedPreferences set/retrieve checkbox with HashMap/For each loop

问题: I was saving the checkbox text and isChecked into the SharedPreferences with using for each loop to get the checkbox value and I use HashMap to store all the value. The c...

问题:

I was saving the checkbox text and isChecked into the SharedPreferences with using for each loop to get the checkbox value and I use HashMap to store all the value.

The code for I save the checkbox text and isChecked:

 HashMap<String,Object> amenityMap = new HashMap<>();

   for(CheckBox checkBox : checkBoxes){
        if(checkBox.isChecked()){
            amenityMap.put(checkBox.getText().toString().trim(),true);
        }
    }

    saveHashMapSharedPreferences(parentActivity, amenityMap, Amenity.AMENITY_DETAILS,Amenity.AMENITY_DETAILS);

Method for SharedPreference:

public static void saveHashMapSharedPreferences(Activity parentActivity,HashMap<String,Object> amenityMap,String spType, String key) {
    SharedPreferences appSharedPrefs = parentActivity.getSharedPreferences(spType, Context.MODE_PRIVATE);

    SharedPreferences.Editor prefsEditor = appSharedPrefs.edit();

    Gson gson = new Gson();
    String json = gson.toJson(amenityMap); //tasks is an ArrayList instance variable
    prefsEditor.putString(key, json);
    prefsEditor.apply();
}

The picture below is the checkbox value save in SharedPreferences .xml:

enter image description here

So the key of it is amenityDetails, the value of checkbox are all there.

How do I can retrieve the checkbox value from this SharedPreference and set back to the checkbox where it is isChecked?


回答1:

First of all change following:

HashMap<String,Object> amenityMap = new HashMap<>();

to

HashMap<String,Boolean> amenityMap = new HashMap<>();

Change your for each loop as follows:

for(CheckBox checkBox : checkBoxes){
     amenityMap.put(checkBox.getText().toString().trim(),checkBox.isChecked());    
}

You can then retrieve values as follows:

SharedPreferences appSharedPrefs = parentActivity.getSharedPreferences(spType, Context.MODE_PRIVATE);
Type type = new TypeToken<Map<String, Boolean>>(){}.getType();
Map<String, Boolean> storedAmenityMap = gson.fromJson(appSharedPrefs.getString(key,""), type);

Then whenever you want to set the Checkbox state:

checkBoxObj.setChecked(storedAmenityMap.get(checkBoxObj.getText()));

回答2:

First your HashMap should be HashMap<String, boolean>. To restore, you can also use Gson to parse saved data to HashMap again and use your restored HashMap to restore CheckBox states

Type collectionType = new TypeToken<HashMap<String, boolean>>(){}.getType();
HashMap<String, boolean> hashMap = gson.fromJson(appSharedPrefs.getString(key,""), collectionType);
  • 发表于 2018-07-11 18:02
  • 阅读 ( 323 )
  • 分类:sof

条评论

请先 登录 后评论
不写代码的码农
小编

篇文章

作家榜 »

  1. 小编 文章
返回顶部
部分文章转自于网络,若有侵权请联系我们删除