Search code examples
javaandroidsharedpreferencesandroid-preferenceslistpreference

sharedPref.getString() picking value from ListPreference's entries instead of entryValues


I have a ListPreference in my activity:

<ListPreference
        android:key="pref_rValue"
        android:entries="@array/r"
        android:summary="***"
        android:entryValues="@array/rValues"
        android:title="Choose"
        android:defaultValue="2"/>

whose android:entries="@array/r" and android:entryValues="@array/rValues" are defined separately in strings.xml like this:

    <string-array name="r">
        <item>0.5 km</item>
        <item>1 km</item>
        <item>2 km</item>
        <item>5 km</item>
        <item>10 km</item>
    </string-array>

    <string-array name="rValues">
        <item>0.5</item>
        <item>1.0</item>
        <item>2.0</item>
        <item>5.0</item>
        <item>10.0</item>
    </string-array>

Key defined in SettingActivity: public static final String KEY_PREF_SYNC_CONN = "pref_rValue";

Here's how I'm using the key and then trying to get the value of this ListPreference in MainActivity:

SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(this);
String rValue = sharedPref.getString(SettingsActivity.KEY_PREF_SYNC_CONN, "5");
Toast.makeText(getBaseContext(), "rValue: " + rValue, Toast.LENGTH_SHORT).show();

but when I'm trying to use rValue string as a Double, I'm getting this error: java.lang.NumberFormatException: Invalid double: "2 km" and the Toast above is also showing "rValue: 2 km".

I want to know that why instead of taking value from android:entryValues="@array/rValues", it is taking value from android:entries="@array/r"?

Please help me with this issue.


Solution

  • It was a really simple and silly issue.

    I just uninstalled the app and after installing it again, everything worked fine.

    But, I would love to know that how to ensure that something like this doesn't happen in the future again.