Запись ListPreference извлекается как индекс вместо строкового значения.

Я пытаюсь сделать приложение, которое будет прогнозировать данные о погоде в ближайшие 7 дней. Я добавляю действие настроек, в котором пользователь может изменить единицу измерения температуры на градусы Фаренгейта или метрические единицы.

Я определил это как ListPreference с записями, взятыми из массива со значениями метрики и Фаренгейта, как показано ниже:

<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent" android:layout_height="match_parent">
<!--location preference:-->
    <EditTextPreference
        android:key="@string/pref_location_key"
        android:title="@string/locTitle"
        android:defaultValue="@string/pref_location_default"
        android:inputType="text"
        android:singleLine="true"
        android:summary="enter location"/>



    <!--temperature unit preference:-->

 <ListPreference android:key="@string/pref_units_key"
                 android:defaultValue="@string/pref_units_metric"
                 android:title="Temperature Unit"
                 android:summary="select a temperature unit"
                 android:entries="@array/units"
                 android:entryValues="@array/indx"/>




</PreferenceScreen>

Это ресурс массива, который содержит записи с индексами этих записей,

<?xml version="1.0" encoding="utf-8"?>
<resources>

    <string-array name="units">

        <item>metric</item>
        <item>Fahrenheit</item>

    </string-array>

    <string-array name="indx">
        <item>0</item>
        <item>1</item>

    </string-array>


</resources>

Проблема заключается в том, что при изменении предпочтения температуры в переменной предпочтения сохраняется значение строки индекса (либо «0», либо «1»), а не значение индекса входа, которое является Фаренгейтом или метрикой. Когда я пытаюсь проверить единицы измерения с помощью оператора if, приложение не распознает значение единиц, если я не использую строку индекса вместо строки ввода,

Вот где я пытаюсь проверить устройство,

private String formatHighLows(double high, double low, String unitType) {

        if (unitType.equalsIgnoreCase(getString(R.string.pref_units_imperial))) {
            high = (high * 1.8) + 32;
            low = (low * 1.8) + 32;
        } else if (!unitType.equals(getString(R.string.pref_units_metric))) {
            Log.d(LOG_TAG, "Unit type not found: " + unitType);
        }

        // For presentation, assume the user doesn't care about tenths of a degree.
        long roundedHigh = Math.round(high);
        long roundedLow = Math.round(low);

        String highLowStr = roundedHigh + "/" + roundedLow;
        return highLowStr;
    }

pref_units_imperial содержит строку по Фаренгейту, но это выражение if не распознается, если оно не записано как

if (unitType.equalsIgnoreCase ("1")), unitType has been fetched from the shared preferences previously and sent to the method. 

Вот класс настроек, который я использую,

public class SettingsActivity extends PreferenceActivity
        implements Preference.OnPreferenceChangeListener {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
// Add 'general' preferences, defined in the XML file
// TODO: Add preferences from XML
   addPreferencesFromResource(R.xml.pref_general);
   bindPreferenceSummaryToValue(findPreference(getString(R.string.pref_location_key)));

        bindPreferenceSummaryToValue(findPreference (getString(R.string.pref_units_key))); //this will find the preference value associated with locKey key and pass it to be saved in the shared preferences

    //we are just getting a reference to the preference, we are not fetching any data from it.


    }

    private void bindPreferenceSummaryToValue(Preference preference) { //receives user preference
// Set the listener to watch for value changes.
        preference.setOnPreferenceChangeListener(this);

// Trigger the listener immediately with the preference's
// current value.
        onPreferenceChange(preference,
                PreferenceManager
                        .getDefaultSharedPreferences(preference.getContext()) //conetxt from which this is called. (returns all shared preferences in the app, so you need to distinguish
                        .getString(preference.getKey(), "")); //the key of the setting that has been changed
    }
    @Override
    public boolean onPreferenceChange(Preference preference, Object value) {
        String stringValue = value.toString();

        if (preference instanceof ListPreference) {
            // For list preferences, look up the correct display value in
            // the preference's 'entries' list (since they have separate labels/values).
            ListPreference listPreference = (ListPreference) preference;
            int prefIndex = listPreference.findIndexOfValue(stringValue);
            if (prefIndex >= 0) {
                preference.setSummary(listPreference.getEntries()[prefIndex]); //get the entries we have specified in the array xml by the indices associated with them
            }
        } else {
            // For other preferences, set the summary to the value's simple string representation.
            preference.setSummary(stringValue);
        }
        return true;
    }
}

В этой строке preference.setSummary(listPreference.getEntries()[prefIndex], предполагается получить либо градусы Фаренгейта, либо метрику, но кажется, что он получает "0" или "1", я хочу получить строковое имя unit, я пытался отлаживать приложение, но не мог понять, почему оно присваивает значение индекса вместо записи.

Кто-нибудь может помочь мне решить эту проблему?

Любая помощь приветствуется.

Спасибо.


comment
Вы решили эту проблему? Если нет, вы только что пытались добавить строковые значения (не как ссылку из strings.xml) в качестве значения записи?   -  person shark1608    schedule 30.07.2015
comment
@dania, тебе удалось найти решение?   -  person HX_unbanned    schedule 08.04.2021