1

Here's the gist of my problem code:

String from = extra.getString("from");
Log.d("Cat", from);  //debugs as edit
if(from == "edit") {
  Log.d("Cat", "Edit");
} else {
  Log.d("Cat", "Not Edit");
}

It would go to "Not Edit"

In the calling activity I have

cIntent.putExtra("from", "edit");
startActivity(cIntent);

If I changed all that up to getInt and passed 1, it debugs as Edit, and if passed 2, debugs as Not Edit.

I don't understand whats going on. I can live with it if I need to, but I feel like I'm missing something very basic here.

Thanks.

spuppett
  • 547
  • 10
  • 26

4 Answers4

1

In Java you need to compare strings as follows,

if(from.equal ( "edit") ) 
{
  Log.d("Cat", "Edit");
} 
else 
{
  Log.d("Cat", "Not Edit");
}

"==" is used to compare object, not values.

Lucifer
  • 29,392
  • 25
  • 90
  • 143
1

Use the equals method:

if(from.equals("edit")) {
  Log.d("Cat", "Edit");
} else {
  Log.d("Cat", "Not Edit");
}
Metro Smurf
  • 37,266
  • 20
  • 108
  • 140
  • It's been so long since I've taken any Java classes. equals briefly crossed my mind but then vanished. Thanks for the example. – spuppett Feb 09 '12 at 04:37
  • Coming from a C# background, I just banged my head on my desk not 3 hours ago on this very problem while abusing my droid. – Metro Smurf Feb 09 '12 at 04:59
0

In Java when you compare using ==, it compares reference ID(pointer) between objects. In case of numeric object like int, it's value is it id. However, with String two identical strings may have different IDs. So when you compare them using ==, it will return false since it's different object.

If you use firstString.equal(secondString) of sorts, it will take the value of that string and compare using it.

Hope this answer your question, long story short never compare string using ==.

RobGThai
  • 5,937
  • 8
  • 41
  • 59
0

You should use str.equalsIgnoreCase(String s) when comparing strings because equals method is primarily used to compare objects, and in some cases it cannot compare two exactly the same strings as it should

Lucifer
  • 29,392
  • 25
  • 90
  • 143
luciferche
  • 134
  • 9