5

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!

user1725145
  • 3,993
  • 2
  • 37
  • 58
Dadi
  • 77
  • 1
  • 3
  • If you have different values, you must have different keys. Why dont you use values as prefix or suffix of your keys? – Mustafa Genç Sep 21 '12 at 11:57
  • ok, i will try that out right now. im not quite sure what you mean :/ i tried to use my values as prefix and my list wasnt populated at all. i switched "recept" with s_product is my logic wrong? or am i missing something? – Dadi Sep 21 '12 at 12:16

1 Answers1

9

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);
    }
knvarma
  • 974
  • 5
  • 6