-4
    savedInstanceState = getIntent().getExtras();
    String type = savedInstanceState.getString(TYPE);
    if(type == "tree")
    {
        setContentView(R.layout.activity_sound_tree);
    }
    else
    {
        TextView tv = (TextView) findViewById(R.id.heading_sound);
        tv.setText("'"+type+"'");
    }

I have used this code in the second activity. I know for sure that type == tree. So I do not understand why the first "if" block fails. It always goes to the "else" block, even though I am 100% sure that type == "tree". Can someone point me in the right direction?

Advait Saravade
  • 3,029
  • 29
  • 34

3 Answers3

3

Never compare string values with the == operator. Use the equals method instead.

The == operator compares object by references, not by values.

Javadoc: http://docs.oracle.com/javase/7/docs/api/java/lang/Object.html#equals(java.lang.Object)

Fixed code:

savedInstanceState = getIntent().getExtras();
String type = savedInstanceState.getString(TYPE);
if(type.equals("tree"))
{
    setContentView(R.layout.activity_sound_tree);
}
else
{
    TextView tv = (TextView) findViewById(R.id.heading_sound);
    tv.setText("'"+type+"'");
}
Sandro Munda
  • 39,921
  • 24
  • 98
  • 123
0

This looks like classic String comparison question, try

"tree".equals(type); // This is also safe from NullPointerException since you are comparing type with a constant 'tree', which is not null

Why Equals?

A detailed explanation regarding using == vs equals() can be found here

Community
  • 1
  • 1
sanbhat
  • 17,522
  • 6
  • 48
  • 64
0

use

type.equals("tree")

instead of

type == "tree"

Reason

equls method check the values of the object where == operator check whether they are the same instance of object.

stinepike
  • 54,068
  • 14
  • 92
  • 112