androidsharedpreferencesandroid-preferencesandroid-settings

How to get textual entries from Android SharedPreference?


I want to retrieve the names of classes as V, VI, VII from the preferences, however, I am getting them in the format 5,6,7 when I try to fetch it.

Values are stored as follows

<string name="pref_standard">Standard</string>
<string-array name="pref_standard_list_titles">
    <item>V</item>
    <item>VI</item>
    <item>VII</item>
    <item>VIII</item>
    <item>IX</item>
    <item>X</item>
    <item>XI</item>
    <item>XII</item>
</string-array>
<string-array name="pref_standard_list_values">
    <item>5</item>
    <item>6</item>
    <item>7</item>
    <item>8</item>
    <item>9</item>
    <item>10</item>
    <item>11</item>
    <item>12</item>
</string-array>

The preference is declared as

<ListPreference
  android:key="standards_list"
  android:title="@string/pref_standard"
  android:defaultValue="10"
  android:entries="@array/pref_standard_list_titles"
  android:entryValues="@array/pref_standard_list_values"
  android:negativeButtonText="@null"
  android:positiveButtonText="@null"/>

I call the value using this

SharedPreferences sharedPref=PreferenceManager.getDefaultSharedPreferences(getActivity());
String standard_name=sharedPref.getString("standards_list","");

This gives only the numeric values which are in "pref_standard_list_values".

How to get the textual values which are in "pref_standard_list_titles"?


Solution

  • Just remove the line

    android:entryValues="@array/pref_standard_list_values"
    

    If you want to translate values in code, use

    String[] texts = getResources().getStringArray(R.array.pref_standard_list_titles);
    String[] values = getResources().getStringArray(R.array.pref_standard_list_values);
    

    And lookup the index of standard_name in values, and its text at that index in texts