How get selected option from ListPreference?
Asked Answered
E

3

7

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.

Ermine answered 20/3, 2012 at 17:50 Comment(0)
B
9
OnPreferenceChangeListener listener = new OnPreferenceChangeListener() {    
    @Override
    public boolean onPreferenceChange(Preference preference, Object newValue) {
        // newValue is the value you choose
        return true;
    }
};

listPreference.setOnPreferenceChangeListener(listener);
Broadcasting answered 20/3, 2012 at 18:6 Comment(0)
C
6

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", "");
Copartner answered 3/1, 2016 at 0:52 Comment(0)
B
2

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

Banka answered 20/3, 2012 at 19:10 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.