Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get Key, not value, of the ListPreference selection - Possible?

Getting the value of the currently selected item in a ListPreference is straightforward:

String selected = sharedPrefs.getString(
    getString(R.string.list_preference_array),
    "default string"
);

But now I need to get the key of the currently selected item, instead. Is this possible?

To clarify, a typical ListPreference definition in the XML file has the following components:

<ListPreference 
    android:key="@string/list_preference_array"
    android:title="Title of ENTIRE list (not seen by user?)"
    android:summary="this is what the user sees in small fonts" 
    android:defaultValue="just in case"
    android:entries="@array/user_friendly_labels" 
    android:entryValues="@array/code_meaningful_strings"
    android:dialogTitle="User Prompt(big font)" 
    android:showDefault="true"
    android:showSilent="true" 
/>

What sharedPrefs.getString() returns is the current selection from android:entryValues. What I am interested in getting is the current selection from android:entries. I mistakenly called it "key" but really it is a "corresponding label", which must be different than actual content.

like image 727
uTubeFan Avatar asked Dec 06 '22 19:12

uTubeFan


1 Answers

A bit of a guess:

int index = mylistpreference.findIndexOfValue(selected)  // <- selected taken from your code above
String entry = mylistpreference.getEntries()[index];
like image 76
Erik Avatar answered Dec 22 '22 00:12

Erik