I have encountered a problem in my Android application. The problem is that for some reason, I can't retrieve the string of a ListPreference
from my preferences.xml
file. Here's the code I tried:
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(); } }
Whenever it gets to the second if/else statement, it directly goes to the else statement. I don't know why it is doing this. I have searched SO and Google, but with no avail. I basically hit a brick wall. Any help regarding this problem would be highly appreciated.
This question is related to
java
android
sharedpreferences
All your exercise conditionals are separate and the else is only tied to the last if statement. Use else if
to bind them all together in the way I believe you intend.
Source: Stackoverflow.com