Reputation: 2192
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.
Upvotes: 7
Views: 9929
Reputation: 1632
OnPreferenceChangeListener listener = new OnPreferenceChangeListener() {
@Override
public boolean onPreferenceChange(Preference preference, Object newValue) {
// newValue is the value you choose
return true;
}
};
listPreference.setOnPreferenceChangeListener(listener);
Upvotes: 9
Reputation: 755
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", "");
Upvotes: 6
Reputation: 21
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
Upvotes: 2