androidlistpreference

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 {
             ...................

Solution

  • 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.