0

I am facing weird situation here.

Following routine is called after I close my preference activity.

SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
String tmp = preferences.getString("unit", "C");
CommonTool.temperatureUnit = tmp;

What it does is, getting the settings that I made from the preference activity and I am storing it to a global variable called CommonTool.temperatureUnit. In this case, value "C" is assigned to it.

Fine by now.

In side the CommonTool class, I have a function which returns a temperature in Celsius or Fahrenheit depends on the user preference, I got from the preference activity.

public static String getCommonTemperature(int celsius) {
    int ret;

    if (temperatureUnit == "C") {
        ret = celsius;
    }
    else {
        ret = (9/5) * celsius + 32;
    }

    return Integer.toString(ret);
}

The thing is.. it keeps fall into else part of it while temperatureUnit contains "C".

Capture while in debug mode

Does anyone have any idea? Thanks in advance.

Harry
  • 709
  • 1
  • 6
  • 16
  • Do you ever set that preference to F for example? How? Where? Show also that code – ddb Aug 20 '16 at 06:40
  • 2
    use if (temperatureUnit.equalsIgnoreCase("C")){....} – Silambarasan Poonguti Aug 20 '16 at 06:41
  • The `==` operator checks whether the references to the objects are equal or not. Read [this](http://stackoverflow.com/questions/767372/java-string-equals-versus) for better understanding. – Bee Aug 20 '16 at 06:55
  • I am very surprised that "==" does not compare the value. Thanks all. This issue is duplicate of "How do I compare strings in Java" as Mike said. – Harry Aug 20 '16 at 13:27

1 Answers1

0

Try this..

public static String getCommonTemperature(int celsius) { int ret;

if (temperatureUnit.equalsIgnoreCase("C")) {
    ret = celsius;
}
else {
    ret = (9/5) * celsius + 32;
}

return Integer.toString(ret);

}

Silambarasan Poonguti
  • 9,386
  • 4
  • 45
  • 38