Question

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.

Was it helpful?

Solution

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

listPreference.setOnPreferenceChangeListener(listener);

OTHER TIPS

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

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top