Search code examples
javaandroidstringbooleanlistpreference

Get keyValue from ListPreference


Following problem:

preferences.xml:

    <ListPreference
        android:title="titel"
        android:summary="summary"
        android:key="remove_onclick"
        android:entries="@array/removeOnclick"
        android:entryValues="@array/removeOnclick_value"
        android:defaultValue="3"/>

My question is, how I can get the Value (1, 2, or 3) to use it with an if-condition in my MainActivity.java

    SharedPreferences sharedConfig = PreferenceManager.getDefaultSharedPreferences(this);
    String removeOnklick = sharedConfig.getString("remove_onclick", "3");

This does not work!

Caused by: java.lang.ClassCastException: java.lang.Boolean cannot be cast to java.lang.String at com.notification.app.SettingsActivity.onCreate(SettingsActivity.java:14)

SettingsActivity:

@Override
public void onCreate(Bundle savedInstanceState){
    super.onCreate(savedInstanceState);
    addPreferencesFromResource(R.xml.preferences);
    PreferenceManager.setDefaultValues(this, R.xml.preferences, false);
 }

EDIT strings.xml

<string-array name="removeOnclick">
    <item>Always</item>
    <item>Never</item>
    <item>Always ask</item>
</string-array>

<string-array name="removeOnclick_value">
    <item>1</item>
    <item>2</item>
    <item>3</item>
</string-array>

And I also have 2 booleans which work perfectly.

    boolean playSound = sharedConfig.getBoolean("sound_on_create", false);
    boolean vibrate = sharedConfig.getBoolean("vibrate_on_create", false);

Update:

I just had to delete the cache and the memory...


Solution

  • Firstly, this line should be placed in MainActivity's onCreate method:

    PreferenceManager.setDefaultValues(this, R.xml.preferences, false);
    

    And, to get the value from the ListPreference in SettingsActivity:

    ListPreference pref = findPreference("remove_onclick");
    String value = pref.getValue();
    if (value.equals("3")){
        // do something here with value 3
    } 
    

    If you want to get the value from MainActivity, call:

        SharedPreferences sharedConfig = PreferenceManager.getDefaultSharedPreferences(this);
        String removeOnklick = sharedConfig.getString("remove_onclick", "3");
        if(removeOnklick.equals("1"){
               // do something here with value 1
       }