How to add new value to listpreference and save it? - android

I have a list Preference that created from resource xml. I added preference that created dialog in which user can add value to listPreference.
using those methods i added new value:
entries = getEntries();
entryValues = getEntryValues();
when user is adding values to listpreference, its displayed. But when preferenceScreen is recreating new value disappearing.
How can i save those new values?

Problem is that when you're reopening your PreferenceScreen, it loads the ListPreference's values from XML. You can change this behavior using the setEntries() and setEntryVaues() methods of ListPreference. Of course you need to somehow store all the values and their indexes that your users enter. You can use databases or SharedPreferences for it. Hope this helps.
EDIT
Saving the value of a ListPreference into the SharedPreferences:
preferences.edit().putString(listPreference.getKey(), listPreference.getValue());

Related

Is it possible to set the default value of an integer sharedpreference as an empty field?

I'm using SharedPreferences to save multiple values from multiple Activities and Fragments and reuse them in various others. This works fine so far.
I mostly save Integers. Is it possible to set the default value of such a SharedPreference to be empty, so when the value is shown in a TextView, the TextView will be empty?
I want this for user convenience, so the user doesn't have to delete the default value in the field, if he wants to change it.
Here is an example of what I mean:
SharedPreferences sharedPref = getSharedPreferences("Datenspeicher", Context.MODE_PRIVATE);
int Stk_jahr = sharedPref.getInt("sp_stueckzahl", 0);
Stueckzahl.setText(String.valueOf(Stk_jahr));
In this example, if no value is saved in sp_stueckzahl, die TextView Stueckzahl will show a 0. I would prefer it to be empty.
Thank you

Use RingtoneManager with custom raw files

I want to use RingtoneManager (or create a custom similar class if not possible) to choose one of my custom list of raw files (I want to show only my files not the default list including my files).
I am used to use this way to pick ringtone How to bring up list of available notification sounds on Android but this time I want to show my custom list of ringtones.
If you want to do this in some kind of settings, you can use ListPreference for letting the user choose a melody. Then you just need to populate your preference in your code; you do this in the following manner:
ListPreference listPreference = (ListPreference) findPreference("yourPreferenceName");
//Now you need to retrieve your melodies from res/raw folder and get their names and id's
ListPreference needs two things to function properly: entries, and entry values. Entries are what the user sees when he opens the list (in your case, names of melodies). And the entry values are the values that will be saved in the default SharedPreference (read a little about using preferences from which ListPreference is derived). All you need to do now is to create entries and entryValues:
CharSequence entries = new CharSequence[numberOfMelodies];
CharSequence entryValues = new CharSequence[numberOfMelodies];
And fill them up manually or inside a loop.
After that just do
listPreference.setEntries(entries);
listPreference.setEntryValues(entryValues);
And get the selected melody's id from SharedPreference wherever you want in your app and use it. (Preference saves the new selection in the default SharedPreference for you automatically every time, you don't need to worry about that).

Reset specific preferences Android

I've got a number of preferences that I want to reset back to the defaults specified in my preferences xml file.
I do not want to reset all of my preferences - just a few select ones.
I've tried:
key=getResources().getString(R.string.myPref);
sharedPreferences.edit().remove(key).commit();
This clears the preference. However when my program then tries to pick the preference up
String myPref = sharedPreferences.getString(key, "");
It just returns the empty string.
How do I get the value from the XML file?
Thanks
Adding more complete code sample that I've been debugging:
//Get preferences
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(activity);
//Get preference key
key=getResources().getString(R.string.myPref);
//Get preference value
String myPref = sharedPreferences.getString(key, ""); // Returns a value that has been entered by a user
//Clear preference
sharedPreferences.edit().remove(key).commit();
//Reset preferences to default values - without overwritting all
PreferenceManager.setDefaultValues(currentContext, preferences, false);
//Get preference value again
String myPref = sharedPreferences.getString(key, ""); // Returns an empty string
Try PreferenceManager.setDefaultValues(this, R.xml.preferences, false);
This is save as the last parameter ensures that user changed entries don't get overridden.
getDefaultSharedPreferences(Context).setDefaultValues(this, R.xml.preference, true);
Be sure to set last argument readAgain to true.
This will force to re-read the default values. If false, this method sets the default values only if this method has never been called in the past (or if the KEY_HAS_SET_DEFAULT_VALUES in the default value shared preferences file is false). To attempt to set the default values again bypassing this check, set readAgain to true.
I realise this question is kind of old, but hopefully this answer might help future viewers. It really helped me.
Quoting the answer:
Try to call the setter of the preference itself instead updating it on your own:
E.g. EditTextPreference.setText(). So the preference itself updates it's own value too. If you do the update on your own the preference will not fetch the new value because it doesn't even know that the persisted value has changed.
If you have a PreferenceFragment, you can get the preference with PreferenceFragment.findPreference().
If you have a PreferenceActivity, you can get the preference with PreferenceActivity.findPreference().
You call that with the preference key you assigned in your settings XML file and you get an instance of the corresponding preference. Then you cast it to a CheckBoxPreference, EditTextPreference, etc (the type you set in your XML file).
My personal adaptation:
Note: I was using this in a PreferenceFragment extended class, therefore the this.getActivity().
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this.getActivity());
preferences.edit().remove(getResources().getString(R.string.pref_username)).apply();
EditTextPreference usernamePref = (EditTextPreference) findPreference(getString(R.string.pref_username));
usernamePref.setText("");
Hope it helps!

Create new preference and persist it?

I'm trying to create a new CheckBoxPreference under a PreferenceGroup for displaying tags. The plan is to add the tags with code like this:
for(Tag t : tags) {
pref = new CheckBoxPreference(FoodhunterCredentials.this);
boolean isChecked = wasChecked(t.getName());
pref.setTitle(t.getName());
pref.setSummary(t.getDescription());
pref.setChecked(isChecked);
pref.setPersistent(true);
Log.d("Credentials", String.format("Adding checkbox %s -%schecked", t, isChecked ? " " : " not "));
tagsGroup.addPreference(pref);
}
But after closing the activity the new checkboxes are gone. Is there a way for persisting the newly created preferences? To be clear: This is not about storing a new value in a defined preference, this is about storing a new created preference.
You can use DB to store all your tags (this is preferable).
Or, if you don't want to use DB for some reason, you can hack with SharedPreferneces in a next way:
Create empty string preference named "tags" (this should not be visible in your PreferenceActivity).
When user adds new tag, your will add tag name to "tags" string preference and save it.
For example, your "tags" string may look like "java;android;helper;europe". You'll need to make duplication checks and parsing yourself. Of cause you'll need to automatically populate your PreferenceScreen in onCreate() method with CheckBoxPreference for each tag, but you already know how to do it.
Yes, and in API level 11 (Android 3.0) and higher you can use String Sets in SharedPrefernces. See getStringSet and putStringSet for more details.
You are not able to modify the XML layout files problematically. You can store the fact that you have an extra check-box in the SharedPreferences or Database but there isn't a super-clean way of doing what you want.

Android - ListPreference save to file or on entry click listener?

My application has a preference file, "settings", which contains 10 key/value pairs.
The keys act as titles for the user, and the values are URL's
Both the key and the value are changeable by the user e.g. the first setting looks something like "example" with the value "example.com", when a user changes that setting, the key also changes. So the first setting would become "different_example" with the value "different_example.com". All stored under the "settings" preference file.
I have been managing this so far, by opening a dialog containing the current key/value pairs in an ArrayList that has an onItemClickListener that pops up a second dialog containing another ArrayList of the possible key/value pairs. When the new item is clicked, I remove the current setting, add the new one, then re-populate the initial ArrayList with the new settings. This works and allows both the key and value to be simultaneously changed and updated, however it looks awkward with the two dialogs.
I'd like to switch this all over to ListPreferences. As in, have ten different ListPreference items, one for each setting, that when clicked opens the listing of all possible entryValues, and when selected, updates the key from the entry name, and the value from the entry value, and saves this under the same "settings" file. I'm not seeing how to save ListPreferences to a specific file, so that I can call
SharedPreferences settings = getSharedPreferences("settings", 0);
anywhere, though
I've also been looking for some kind of click handler for what to fire when an entry is selected so I can manually update the "settings" file, but not having any luck. Does such a thing exist? Or is there another way for me to do this?
Edit: I can use OnPreferenceChange to manually set the new value, but this doesn't return the value name, e.g. the value used in the human-readable list. Any ideas on how to get that?
See if this can give you a jump start: How do I get preferences to work in Android?
If you customize your ListPreference and come across something like this How to make a Preference not save to SharedPreferences?
Ahh, well this seems incredibly backwards, but what I've done is set each ListPreference to have an onPreferenceChangeListener, and each entryValue for the ListPreference to contain the name as well as the value separated by an arbitrary string. Then in the onPreferenceChange, I can reference the new value (which now also contains the new key) turn it into a String[] split at the arbitrary separator, then assign the String[] 0 index as the new key, and the 1 index as the new value by using SharedPreferences.Editor after removing the original setting.
Unless there's some way to return the Entry name from the ListPreference's entryValues array, or to specify ListPreference to save to a specific settings file, neither of which is documented, then this will probably be the best solution for me.

Categories

Resources