1
//intent.putExtra(EXTRA_MESSAGE, "abc");
intent.getStringExtra(Home.EXTRA_MESSAGE) == "abc" // false
intent.getStringExtra(Home.EXTRA_MESSAGE) == getString(R.string.abc) //false (with R.string.abc=="abc")

String abc = "abc";
intent.getStringExtra(Home.EXTRA_MESSAGE) == abc //false

Why everything is false? If I print the values with a toast they're apparently identical.

Thanks.

user3223863
  • 135
  • 3
  • 12

5 Answers5

2

You compare the values of two java String's with .equals:

str1.equals(str)

In this context, == compares whether those two String's are the same objects, and they are not, thus evaluates to false.

Peter Pei Guo
  • 7,770
  • 18
  • 35
  • 54
1

Well first and foremost, you can't compare strings with == ...

You need to be comparing two strings with string1.equals(string2)

Then you should get a "true" result.

hope this helps. Good luck :)

Alex K
  • 8,269
  • 9
  • 39
  • 57
0

== compare whether both the string objects are same.(I.e address of object)

equals () method compare whether both the string objects have same value or not.

Rustam
  • 6,485
  • 1
  • 25
  • 25
0

Try to understand this code and the results below to see the difference between == and equals(). Then you'll see why equals() is usually what you want for comparing strings.

String string1 = "android";
String string2 = "android";
String string3 = new String("android");

if(string1 == string2){
   System.out.print("String1 == String2");
}else{
   System.out.print("String1 != String2");
}

if(string1.equals(string2)){
   System.out.print("String1 equals String2");
}else{
   System.out.print("String1 not equals String2");
}

if(string1 == string3){
   System.out.print("String1 == String3");
}else{
   System.out.print("String1 != String3");
}

if(string1.equals(string3)){
   System.out.print("String1 equals String3");
}else{
   System.out.print("String1 not equals String3");
}

if(string2 == string3){
   System.out.print("String2 == String3");
}else{
   System.out.print("String2 != String3");
}

if(string2.equals(string3)){
   System.out.print("String2 equals String3");
}else{
   System.out.print("String2 not equals String3");
}

Result :

>> String1 == String2
>> String1 equals String2
>> String1 != String3
>> String1 equals String3
>> String2 != String3
>> String2 equals String3
Alex Blakemore
  • 11,301
  • 2
  • 26
  • 49
Haresh Chhelana
  • 24,720
  • 5
  • 57
  • 67
0

Try out equals() Instead == like:

//intent.putExtra(EXTRA_MESSAGE, "abc");
intent.getStringExtra(Home.EXTRA_MESSAGE).equals("abc");
intent.getStringExtra(Home.EXTRA_MESSAGE).equals(getString(R.string.abc));

String abc = "abc";
intent.getStringExtra(Home.EXTRA_MESSAGE).equals(abc);

Note: If you have set values using putExtra(key, String) then you can simply get values using intent.getString(key).

Pratik Butani
  • 60,504
  • 58
  • 273
  • 437