无法从首选项(设置)中检索字符串

时间:2013-12-31 22:25:08

标签: java android sharedpreferences

我的Android应用程序遇到了问题。问题是由于某些原因,我无法从ListPreference文件中检索preferences.xml的字符串。这是我试过的代码:

private void showUserSettings() {
    SharedPreferences sharedPrefs = PreferenceManager
            .getDefaultSharedPreferences(this);

    try {

        String feet = sharedPrefs.getString("feet", "NULL");
        int intfeet = Integer.parseInt(feet);
        int intinches = Integer.parseInt(sharedPrefs.getString("feet", "NULL").trim());
        int weight = Integer.parseInt(sharedPrefs.getString("weight", "NULL").trim());
        int age = Integer.parseInt(sharedPrefs.getString("age", "NULL").trim());
        double calories;
        double inches = ((intfeet * 12) + intinches);
        if (gender.equals("Female")) {
            //BMR = 655 + ( 4.35 x weight in pounds ) + ( 4.7 x height in inches ) - ( 4.7 x age in years )
            calories = 655 + (4.35 * weight) + (4.7 * inches) - (4.7 * age);
        }
        else {
            //66 + ( 6.23 x weight in pounds ) + ( 12.7 x height in inches ) - ( 6.8 x age in years )
            calories = 66.5 + (6.23 * weight) + (12.7 * inches) - (6.8 * age);
        }
        //ListPreference listPreference = (ListPreference) findPreference("exercise");
        //CharSequence currText = listPreference.getEntry();
        String exercise = sharedPrefs.getString("exercise", "NULL").toString();
        if (exercise.equals("Sedentary")) {
            double sedentary = calories * 1.2;
            Toast.makeText(getApplicationContext(), sedentary + "", Toast.LENGTH_LONG).show();
        }
        if (exercise.equals("Light")){
            double light = calories * 1.375;
            Toast.makeText(getApplicationContext(), light + "", Toast.LENGTH_LONG).show();
        }
        if (exercise.equals("Moderate")){
            double moderate = calories * 1.55;
            Toast.makeText(getApplicationContext(), moderate + "", Toast.LENGTH_LONG).show();
        }
        if (exercise.equals("Very active")) {
            double veryactive = calories * 1.725;
            Toast.makeText(getApplicationContext(), veryactive + "", Toast.LENGTH_LONG).show();
        }
        if (exercise.equals("Extra active")) {
            double extraactive = calories * 1.9;
            Toast.makeText(getApplicationContext(), extraactive + "", Toast.LENGTH_LONG).show();
        }
        else {
            Toast.makeText(getApplicationContext(), "Uh oh", Toast.LENGTH_SHORT).show();
        }
    }catch (Exception e) {
        e.printStackTrace();
    }
}

每当它到达第二个if / else语句时,它直接转到else语句。我不知道为什么这样做。我搜索了SO和谷歌,但没有用。我基本上打了一堵砖墙。任何有关此问题的帮助都将受到高度赞赏。

1 个答案:

答案 0 :(得分:1)

你所有的运动条件都是分开的,而else只与最后一个if语句联系在一起。使用else if以我认为您打算的方式将它们绑定在一起。