How get selected option from ListPreference? - android

I have ListPreference and it contains for example 5 options and I want to save one of this value to SharedPreferences when user selects it. How can I do it?
btw. I know how to save value to SharedPreferences, but I don't know how to get that value when user selects one of them.

OnPreferenceChangeListener listener = new OnPreferenceChangeListener() {
#Override
public boolean onPreferenceChange(Preference preference, Object newValue) {
// newValue is the value you choose
return true;
}
};
listPreference.setOnPreferenceChangeListener(listener);

I access mine like this.. Please see example below
In my preference.xml file:
<ListPreference
android:key="SQS_ENDPOINT"
android:dialogTitle="Choose an option please"
android:entries="#array/sqsItems"
android:entryValues="#array/sqsValues"
android:title="SQS Endpoints" >
</ListPreference>
my String.xml:
<string-array name="sqsItems">
<item>US East (N. Virginia)</item>
<item>Asia Pacific (Singapore)</item>
<item>Asia Pacific (Tokyo)</item>
</string-array>
<string-array name="sqsValues">
<item>sqs.us-east-1.amazonaws.com</item>
<item>sqs.ap-southeast-1.amazonaws.com</item>
<item>sqs.ap-northeast-1.amazonaws.com</item>
</string-array>
And then I get the selected value like this from anywhere:
SharedPreferences pref = PreferenceManager
.getDefaultSharedPreferences(context);
String END_POINT = pref.getString("SQS_ENDPOINT", "");

In your xml file you provide SharedPreferences key for your list.
<ListPreference
android:key="SHARED_PREFS_KEY"
...
/>
Every time user selects item from the list it is saved to the default SharedPreferences

Related

ANDROID Preferences List Preference change values dynamically

I am trying to change the entryvalue of a listpreference depending on wether a checkbox is ticked or not...
SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(this);{
if(sharedPrefs.getBoolean("french", false))
{
Preference newsPref = (Preference) findPreference("news_feed");
newsPref.setDefaultValue("#array/newsfeedfr");
}
else
{
Preference newsPref = (Preference) findPreference("news_feed");
newsPref.setEntryValues("#array/newsfeed");
}
}
i get errors on the .setEntryValue with this:
The method setEntryValues(String) is undefined for the type Preference
One issue that you have is in how you're referencing your array values. #array/newsfeed is used in XML files, not Java!
You probably want to use getResources().getStringArray(R.array.newsfeed) or similar. Source.
Another issue is that setEntryValues() isn't defined for Preferences, you need to initialise as a ListPreference instead.

how to show selected data into summary of list preferences

i am new to android programming .well in my application i have added the preference class and i am calling the xml preference which is stored in the xml folder of my application.this is the code for it
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android">
<ListPreference android:title="colors" android:key="colors"
android:summary="list of colors to choose from " android:entries="#array/list"
android:entryValues="#array/lvalues"></ListPreference>
</PreferenceScreen>
and in the java class i had written only one line that is this
addPreferencesFromResource(R.xml.prefs);
now i am able to show the preference class and also the list some colors data.
my question is on selecting the list preference it should show me the selected preference in to the summary attribute .currently it is showing me as 'list of colors to choose from'
what i want is to show the selected color say i have selected white the summary should show me as white.
please help me .
Thank you,
maddy.
you can actually do it in xml. Try this:
<ListPreference
android:key="pref_list"
android:title="A list of preferences"
android:summary="%s"
android:entries="#array/pref_list_entries"
android:entryValues="#array/pref_list_entries_values"
android:defaultValue="0" />
your selected value would replace "%s".
For further clarification read this post
In the other code example there is a little bug which causes that the old value is displayed and not the new one.
Here is a working version:
ListPreference splashList = (ListPreference) findPreference("splash");
splashList.setSummary(splashList.getEntry());
splashList.setOnPreferenceChangeListener(new OnPreferenceChangeListener() {
public boolean onPreferenceChange(Preference preference, Object newValue) {
String nv = (String) newValue;
if (preference.getKey().equals("splash")) {
ListPreference splashList = (ListPreference) preference;
splashList.setSummary(splashList.getEntries()[splashList.findIndexOfValue(nv)]);
}
return true;
}
});
You need to extend ListPreference class and specify that in the xml file
class MyListPref extends ListPreference {
public void onClick (DialogInterface dialog, int which) {
this.setSummary(MyListPref.this.getEntry());
}
}
If your Custom Preference class name is com.sample.MyListPref the xml entry will be
<com.sample.MyListPref
android:key="pref_list"
android:title="List Preference"
android:dialogTitle="List Pref Dialog"
android:entries="#array/pref_items"
android:entryValues="#array/pref_items_values"/>
You dont need to do the extend listPreferences. in your PreferencesActivity file put as per my example:
final ListPreference defaultTown=(ListPreference)findPreference(getString(R.string.pref_default_town_key));
Log.i("try",defaultTown.getKey());
defaultTown.setOnPreferenceChangeListener(new OnPreferenceChangeListener() {
public boolean onPreferenceChange(Preference preference, Object newValue) {
Log.i("theApp", "Selected = " + defaultTown.getValue());
defaultTown.setTitle(defaultTown.getValue());
return true;
}
});
on change the value will update the title
when you enter the application you will need to populate the title with your current preference though instead of colors which is set at default in your xml

Android listpreferences, how to save individual preference

I have some list preferences, but I don't know how to save the individual values from the list. How do I do it? Here is what I have
http://i41.tinypic.com/dh4gvo.png
Preference customPref = (Preference) findPreference("notificationPref");
customPref.setOnPreferenceClickListener(new OnPreferenceClickListener() {
public boolean onPreferenceClick(Preference preference) {
SharedPreferences customSharedPreference = getSharedPreferences(
"notifications", Activity.MODE_PRIVATE);
SharedPreferences.Editor editor = customSharedPreference
.edit();
editor.putString("notification",
"The preference has been clicked");
editor.commit();
return true;
}
});
my list click listener is only for the main item in the list preferences page, but not the items in the popup itself. How do I save the choice selected in the popup itself?
This is usually automatic. In your preference screen XML, you should have something like this:
<ListPreference android:title="#string/Title"
android:summary="#string/Summary"
android:key="PreferenceKey"
android:defaultValue="VALUE_2"
android:entries="#array/Entries"
android:entryValues="#array/Values" />
And in your strings.xml:
<string name="Value1">Text for value 1</string>
<string name="Value2">Text for value 2</string>
<string name="Value3">Text for value 3</string>
<string-array name="Entries">
<item>#string/Value1</item>
<item>#string/Value2</item>
<item>#string/Value2</item>
</string-array>
<string-array name="Values">
<item>VALUE_1</item>
<item>VALUE_2</item>
<item>VALUE_3</item>
</string-array>
The "Values" array specify the (string) value saved in preferences, whereas the "Entries" array specify the text of the items displayed to the user. Each time the user select an item, its corresponding value in the "Values" array is saved to preferences under the specified key ("PreferenceKey" in this example).
You can read preferences like this...
SharedPreferences sharedPreferences = getPreferences(MODE_PRIVATE);
String strSavedMem1 = sharedPreferences.getString("key", "Default Value");

ListPreference summary not formatting

I have a ListPreference and I want to show the current entry in the summary. According to the docs for ListPreference.getSummary(), I'm supposed to be able to do this by including %s in the summary string. Unfortunately, the activity just displays the %s in the summary.
The XML is pretty standard:
<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android">
<ListPreference
android:key="displayMode"
android:summary="#string/display_mode_summary"
android:title="#string/display_mode"
android:defaultValue="BOTH"
android:entries="#array/displayModes"
android:entryValues="#array/displayModeValues"
/>
</PreferenceScreen>
The value of the string display_mode_summary is just %s. (The value "BOTH" is present in the displayModeValues array.) If I subclass ListPreference like this:
public final class DisplayModePreference extends ListPreference {
// ...
#Override
public CharSequence getSummary() {
return String.format(super.getSummary().toString(), getEntry());
}
}
then when the preferences activity starts, the current value is correctly interpolated into the summary. But when I click on the preference and select a different value from the dialog, when the dialog closes the summary still shows the now-old value. I need to close the preferences activity and restart it to see the change.
I've tried this in several emulators at different API levels. What do I need to so that the displayed summary always reflects the current value?
You could override "onDialogClosed" as below:
#override
protected void onDialogClosed(boolean positiveResult) {
super.onDialogClosed(positiveResult);
if (positiveResult) {
setSummary(getEntry());
}
}
This will set the summary of your preference to the text of the selected entry.
The original getSummary() in ListPreference only works when getEntries(), getEntryValues() and defaultValue are pre-populated when the Preference screen loads. So it works fine when you use a static fixed list of items, like a <string-array> resource.
But if you are dynamically generating the entries and entryValues at runtime, you need to ensure that these lists are generated when the Preference screen loads in onCreate() and also ensure that the defaultValue is set. Something like this:
SettingsFragment.java
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ListPreference listPreference = (ListPreference) findPreference("dynamiclistItems");
CharSequence[] entryDisplayNames = new CharSequence[3];
entryDisplayNames[0] = "Item A";
entryDisplayNames[1] = "Item B";
entryDisplayNames[2] = "Item C";
CharSequence[] entryValues = new CharSequence[3];
entryValues[0] = "Item A Value";
entryValues[1] = "Item B Value";
entryValues[2] = "Item C Value";
listPreference.setEntries(entryDisplayNames);
listPreference.setEntryValues(entryValues);
if (listPreference.getValue() == null ||
listPreference.getValue().equals("")) {
// There is no stored string in shared prefs.
// The user has not chosen any value. So make
// the summary display a default entry "Item A"
// display name, which is item 0 in the 'entries' list. Info:
// https://stackoverflow.com/questions/5197228/how-to-set-the-default-value-of-a-listpreference
listPreference.setValueIndex(0);
}
}
For static lists that are populated with <string-array>, just ensure that android:defaultValue="..." is defined, and that it points to a valid item in the 'values' array. For example: android:defaultValue="Item A Value"
This will ensure that the android:summary="%s" will work properly for dynamically generated and static lists.

How to retrieve the preference from ListPreference?

I have ListPreference that has 4 choices/options, I want to check for the selected option and make some code(if 1 is selected I do that, if 2 is selected I do other thing ...).
XML:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string-array name="kernel">
<item>TalonDev</item>
<item>Semaphore</item>
<item>SpeedMod</item>
<item>Galaxian</item>
</string-array>
<string-array name="kernel_return">
<item>0</item>
<item>1</item>
<item>2</item>
<item>3</item>
</string-array>
</resources>
Is that true :
choice = prefs.getString("listPref_kernel", "0");
if (choice == "0") {
try {
...................
If you are in a PreferenceActivity:
Retrieve your shared preferences:
SharedPreferences sp = getPreferenceScreen().getSharedPreferences();
and retrieve the value:
String value = sp.getString(key, "default");
Optionally, you can set a SharedPreferences.OnSharedPreferenceChangeListener via
sp.registerOnSharedPreferenceChangeListener(...)
to be notified on any change.

Categories

Resources