[java] Cannot retrieve string(s) from preferences (settings)

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

The answer is


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.


Questions with java tag:

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How much should a function trust another function How to implement a simple scenario the OO way Two constructors How do I get some variable from another class in Java? this in equals method How to split a string in two and store it in a field How to do perspective fixing? String index out of range: 4 My eclipse won't open, i download the bundle pack it keeps saying error log getting " (1) no such column: _id10 " error Instantiating a generic type When to create variables (memory management) java doesn't run if structure inside of onclick listener String method cannot be found in a main class method Are all Spring Framework Java Configuration injection examples buggy? Calling another method java GUI I need to know how to get my program to output the word i typed in and also the new rearranged word using a 2D array Java and unlimited decimal places? Read input from a JOptionPane.showInputDialog box Cannot retrieve string(s) from preferences (settings) strange error in my Animation Drawable Two Page Login with Spring Security 3.2.x Hadoop MapReduce: Strange Result when Storing Previous Value in Memory in a Reduce Class (Java) Got a NumberFormatException while trying to parse a text file for objects Best way for storing Java application name and version properties Call japplet from jframe FragmentActivity to Fragment Comparing two joda DateTime instances Maven dependencies are failing with a 501 error IntelliJ: Error:java: error: release version 5 not supported Has been compiled by a more recent version of the Java Runtime (class file version 57.0) Why am I getting Unknown error in line 1 of pom.xml? Gradle: Could not determine java version from '11.0.2' Error: Java: invalid target release: 11 - IntelliJ IDEA Android Gradle 5.0 Update:Cause: org.jetbrains.plugins.gradle.tooling.util Why is 2 * (i * i) faster than 2 * i * i in Java? must declare a named package eclipse because this compilation unit is associated to the named module How do I install Java on Mac OSX allowing version switching? How to install JDK 11 under Ubuntu? Java 11 package javax.xml.bind does not exist IntelliJ can't recognize JavaFX 11 with OpenJDK 11 Difference between OpenJDK and Adoptium/AdoptOpenJDK OpenJDK8 for windows How to allow all Network connection types HTTP and HTTPS in Android (9) Pie? Find the smallest positive integer that does not occur in a given sequence Error: JavaFX runtime components are missing, and are required to run this application with JDK 11 How to uninstall Eclipse? Failed to resolve: com.google.firebase:firebase-core:16.0.1 How to resolve Unable to load authentication plugin 'caching_sha2_password' issue

Questions with android tag:

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How to implement a simple scenario the OO way My eclipse won't open, i download the bundle pack it keeps saying error log getting " (1) no such column: _id10 " error java doesn't run if structure inside of onclick listener Cannot retrieve string(s) from preferences (settings) strange error in my Animation Drawable how to put image in a bundle and pass it to another activity FragmentActivity to Fragment A failure occurred while executing com.android.build.gradle.internal.tasks Why am I seeing net::ERR_CLEARTEXT_NOT_PERMITTED errors after upgrading to Cordova Android 8? "Failed to install the following Android SDK packages as some licences have not been accepted" error Android Gradle 5.0 Update:Cause: org.jetbrains.plugins.gradle.tooling.util No Creators, like default construct, exist): cannot deserialize from Object value (no delegate- or property-based Creator WebView showing ERR_CLEARTEXT_NOT_PERMITTED although site is HTTPS WARNING: API 'variant.getJavaCompile()' is obsolete and has been replaced with 'variant.getJavaCompileProvider()' GoogleMaps API KEY for testing Can I use library that used android support with Androidx projects. How to allow all Network connection types HTTP and HTTPS in Android (9) Pie? Android Material and appcompat Manifest merger failed Deprecated Gradle features were used in this build, making it incompatible with Gradle 5.0 How to format DateTime in Flutter , How to get current time in flutter? How to change package name in flutter? Failed to resolve: com.android.support:appcompat-v7:28.0 What is AndroidX? Unable to resolve dependency for ':app@debug/compileClasspath': Could not resolve FirebaseInstanceIdService is deprecated installation app blocked by play protect Handling back button in Android Navigation Component Android design support library for API 28 (P) not working Failed to resolve: com.google.firebase:firebase-core:16.0.1 com.google.android.gms:play-services-measurement-base is being requested by various other libraries java.lang.NoClassDefFoundError:failed resolution of :Lorg/apache/http/ProtocolVersion Install Android App Bundle on device Conflict with dependency 'com.android.support:support-annotations' in project ':app'. Resolved versions for app (26.1.0) and test app (27.1.1) differ. How to develop Android app completely using python? Invoke-customs are only supported starting with android 0 --min-api 26 Flutter.io Android License Status Unknown How to open Android Device Monitor in latest Android Studio 3.1 Default interface methods are only supported starting with Android N How can I change the app display name build with Flutter? Error:(9, 5) error: resource android:attr/dialogCornerRadius not found error: resource android:attr/fontVariationSettings not found Flutter does not find android sdk Error - Android resource linking failed (AAPT2 27.0.3 Daemon #0) Error : Program type already present: android.support.design.widget.CoordinatorLayout$Behavior flutter run: No connected devices Cannot inline bytecode built with JVM target 1.8 into bytecode that is being built with JVM target 1.6 Still getting warning : Configuration 'compile' is obsolete and has been replaced with 'implementation' PANIC: Cannot find AVD system path. Please define ANDROID_SDK_ROOT (in windows 10)

Questions with sharedpreferences tag:

Cannot retrieve string(s) from preferences (settings) How can I view the shared preferences file using Android Studio? Android Shared preferences for creating one time activity (example) Android SharedPreferences in Fragment Get Android shared preferences value in activity/normal class How do you save/store objects in SharedPreferences on Android? Save ArrayList to SharedPreferences Where are shared preferences stored? What's the difference between commit() and apply() in SharedPreferences how to use getSharedPreferences in android store and retrieve a class object in shared preference Is it possible to add an array or object to SharedPreferences on Android How to delete shared preferences data from App in Android How to use SharedPreferences in Android to store, fetch and edit values How do I get the SharedPreferences from a PreferenceActivity in Android?