0

This is what I am doing

FIRST ACTIVITY

public void onClick(View v) {
            Intent intent = new Intent(TeamsActivity.this,PakistaniPlayers.class).putExtra("StringName","hello");
            startActivity(intent);  
}

SECOND ACTIVITY

if(getIntent().getStringExtra("StringName")=="hello")
{
  TextView t=(TextView) findViewById(R.id.textView1);
  t.setText(getIntent().getStringExtra("StringName"));
}

Now the code inside the if statement doesn't run but if I run the statements inside the if statement separately I get hello displayed.

Johnny101
  • 11
  • 2
  • 4
    try `if(getIntent().getStringExtra("StringName").equals("hello"))` ... – anil Dec 21 '14 at 15:21
  • Thanks @anil it worked. Any idea what was the problem with using == – Johnny101 Dec 21 '14 at 15:28
  • http://stackoverflow.com/questions/767372/java-string-equals-versus – Adam S Dec 21 '14 at 15:31
  • @Johnny101, `==` compares only the equality of the object, but what we need here is the equality of the content. So as anil said, we have to use `equals` method or `equalsIgnoreCase` method – Panther Dec 21 '14 at 15:33
  • In other words String a == String a is valid, but String a == String b is not valid even if a has the same value as b. == is meant for primitives for the most part. – zgc7009 Dec 21 '14 at 15:35

2 Answers2

1

As @anil already said, you can't compare strings like this in java.

There are three main functions of the String class that can compare two strings with each other:

  • equals
  • equalsIgnoreCase
  • matches
String test1 = "Hello";
String test2 = "hello";

test1.equalsIgnoreCase(test2); //isn't case-sensitive, so true.
test1.equals(test2); //is case-sensitive, so false.
test1.matches("[hH]ello"); //takes regexp, and will, in this case, be true.
test2.matches("[hH]ello"); //takes regexp, and will, in this case, be true.

General hint: If you don't care about whitespace-exact matches, eg: " Hello" should also match "Hello" I would recommend you to always test1.trim() your strings, especially if it's parsed content.

showp1984
  • 378
  • 1
  • 2
  • 13
0

As @Panther said, for String type you should use equals when you want compare content. So the code if(getIntent().getStringExtra("StringName").equals("hello")) works and the code if(getIntent().getStringExtra("StringName")=="hello") does not.

Also, you can call getExtra many times, it always returns the same value.

anil
  • 2,083
  • 21
  • 37