android: is there a way to remove a string from shared preferences by its value instead of its key?
android, preferences, shared
Solution
User your checkbox text as keys of your shared preference file.
SharedPreferences prefs = context.getSharedPreferences(name, mode);
SharedPreferences.Editor editor = prefs.edit();
String key = checkbox.getText();
if(checkbox.isChecked()) {
editor.putString(key, null);
} else {
editor.remove(key);
}
editor.commit();
// if you want to get all the list of checkboxes checked to show in listview
Set<String> keys = prefs.getAll().keySet();
for(String key : keys) {
Log.d(TAG, key);
}
Problem
Pretty much what the title says. I have got a checkbox which on checked puts a string into shared prefs, and when unchecked should remove that same string. I wanted to use the editor.remove but it asks for a key and not a string value and I can't seem to figure it out... the id would be: `"recept" + (fav_popis.getInt("brojanje", 0) + 1)` but that doesn't work between the strings are later used to create a listview! ``` editor.putInt("brojanje", fav_popis.getInt("brojanje", 0) + 1); editor.putString("recept" + (fav_popis.getInt("brojanje", 0) + 1), s_product); ``` any help appreciated. Thank you!