0

Why does my "if" statement not fire?

String something = "";
String category = json_data.getString("den");
Log.e("JSON", "category="+category);            
if (category == "1"){
  something = "Random something";
}

Even if in my logcat I can see JSON:"category=1", the "something" String does not take "Random something" value. This must be some convention in java? Please help.

user1137313
  • 2,390
  • 9
  • 44
  • 91

2 Answers2

4

use:

if (category.equals("1")){
    something = "Random something";
}

or better way to avoid null pointer exception:

if ("1".equals(category)){
    something = "Random something";
}

Also have a look at this link for detail : How do I compare strings in Java?

Community
  • 1
  • 1
M-Wajeeh
  • 17,204
  • 10
  • 66
  • 103
1

You need to do string comparison in Java using the .equals method on the String object. The comparison you are doing is only comparing the references not the actual string values.

Example:

if(category.equals("1")){
    //do amazing stuff
}
Ralph Caraveo
  • 10,025
  • 7
  • 40
  • 52