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!
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.
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.
To retrieve values from shared preferences: SharedPreferences sp = PreferenceManager. getDefaultSharedPreferences(this); String name = sp. getString("Name", ""); // Second parameter is the default value.
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.
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);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With