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:
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?