正在将ListPreference Entry作为索引而不是其字符串值进行检索

时间:2015-03-29 18:32:59

标签: android android-activity sharedpreferences application-settings listpreference

我正在尝试制作一个能够在接下来的7天内预测天气数据的应用程序。我正在添加一个设置活动,用户可以在其中将温度单位更改为华氏度或公制。

我已将此定义为ListPreference,其中的条目取自数组,其值为metric和Fahrenheit,如下所示,

<?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>

问题在于,当温度偏好改变时,存储在首选项变量中的是索引字符串值(&#34; 0&#34;或&#34; 1&#34;)而不是条目索引值是华氏度或公制。当我尝试使用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包含字符串Fahrenheit,但除非将其写为

,否则无法识别此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]中,它应该得到华氏度或公制,但它似乎得到&#34; 0&#34;或&#34; 1& #34;,我想得到单位的字符串名称,我已经尝试调试应用程序,但我不知道为什么它会分配索引值而不是条目。

有人可以帮我解决这个问题吗?

感谢任何帮助。

谢谢。

1 个答案:

答案 0 :(得分:0)

每次更改应用程序的首选项时,清除应用程序数据(存储和缓存)以摆脱旧的首选项数据。