Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

android: is there a way to remove a string from shared preferences by its value instead of its key?

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!

like image 351
Dadi Avatar asked Sep 21 '12 11:09

Dadi


People also ask

What can I use instead of shared preferences in Android?

Jetpack DataStore is a new and improved data storage solution aimed at replacing SharedPreferences. Built on Kotlin coroutines and Flow, DataStore provides two different implementations: Data is stored asynchronously, consistently, and transactionally, overcoming most of the drawbacks of SharedPreferences.

How do you use SharedPreferences in Android to store fetch and edit values?

Shared Preferences allow you to save and retrieve data in the form of key,value pair. In order to use shared preferences, you have to call a method getSharedPreferences() that returns a SharedPreference instance pointing to the file that contains the values of preferences.

How can I get shared preferences data?

To retrieve values from shared preferences: SharedPreferences sp = PreferenceManager. getDefaultSharedPreferences(this); String name = sp. getString("Name", ""); // Second parameter is the default value.

Where are shared preferences stored Android?

Android Shared Preferences Overview Android stores Shared Preferences settings as XML file in shared_prefs folder under DATA/data/{application package} directory. The DATA folder can be obtained by calling Environment.


1 Answers

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);
    }
like image 58
knvarma Avatar answered Oct 02 '22 01:10

knvarma