0

I am passing String extra's to an Intent which is sent to a BroadCastReceiver, and fetching them like:

public void onReceive(Context context, Intent intent) {
    if (intent.hasExtra("type")){
        Log.i("Listener", ":"+intent.getStringExtra("type")+":");

        if (intent.getStringExtra("type") == "start"){  
            Log.i("Listener", "start");
        }
        if (intent.getStringExtra("type") == "end"){    
            Log.i("Listener", "end");
        }
    }
}//end method

this code gives me the following output (as expected):

07-22 10:41:00.038: I/Listener(28678): :start:

What's not expected is that the second if statement never matches, even though type is clearly set correctly. I have seen this a couple of times, and it really is annoying me. This behaviour seems weird, as far as I can tell, I am approaching this in the right way.

Anyone got any ideas?

slinden77
  • 3,378
  • 2
  • 37
  • 35

2 Answers2

3

For String comparison use equals() and not ==.

Change:

if (intent.getStringExtra("type") == "start")
{  
      Log.i("Listener", "start");
}
if (intent.getStringExtra("type") == "end")
{    
     Log.i("Listener", "end");
}

to

if (intent.getStringExtra("type").equals("start")){  
            Log.i("Listener", "start");
        }
        if (intent.getStringExtra("type").equals("end")){    
            Log.i("Listener", "end");
        }

Read this for further info.

Community
  • 1
  • 1
Kazekage Gaara
  • 14,972
  • 14
  • 61
  • 108
2

String is not a primitive data type, so you cannot use the == operator to compare two of them. Instead, try using:

if (intent.getStringExtra("type").equals("start")){  

and

if (intent.getStringExtra("type").equals("end")){    
Raghav Sood
  • 81,899
  • 22
  • 187
  • 195