0

I am trying to pass two variables from one screen to another. From the previous screeen you click a button, 1 or 2 and it passes that value on. It also passes the value 2 as the correct value. I know they are both working as I output each variable on the next screen. Here is the code. It always outputs wrong though.

Intent i = getIntent();
Bundle b = i.getExtras();
String newText = b.getString("PICKED");
String correct = b.getString("CORRECT");
TextView titles = (TextView)findViewById(R.id.TextView01);
if(newText == correct){
titles.setText("Correct" + newText + " " + correct + "");
}
else{
    titles.setText("Wrong" + newText + " " + correct + "");
}
Somk
  • 11,869
  • 32
  • 97
  • 143

3 Answers3

3

because you are not comparing the string. you are comparing if both are pointing to same object.

to compare string use

if(nexText.equals(correct))
Vivek Goel
  • 22,942
  • 29
  • 114
  • 186
0
if(newText == correct)

This will always be false. To compare the contents of two Strings character by character, use the .equals method:

if( newText.equals(correct) )

Using == on objects in Java means you are comparing the values of the memory address stored in these pointers/references. Since they are different String objects, they will never have the same address.

Jems
  • 11,560
  • 1
  • 29
  • 35
0

You don't compare Strings this way, rewrite code this way to get things done:

Intent i = getIntent();
Bundle b = i.getExtras();
String newText = b.getString("PICKED");
String correct = b.getString("CORRECT");
TextView titles = (TextView)findViewById(R.id.TextView01);
if(newText.equals(correct)){
titles.setText("Correct" + newText + " " + correct + "");
}
else{
  titles.setText("Wrong" + newText + " " + correct + "");
}
Aman Alam
  • 11,231
  • 7
  • 46
  • 81