0

I am puzzled as to why the below code always comes up with the toast incorrect even when the two views return the same text.

 @Override
     public void onClick(View view) {
         int intID = view.getId();
         Button button = (Button) findViewById(intID);
         CharSequence message = button.getText().toString();
         Log.i(LOGTAG, (String) message);
         TextView textview = (TextView) findViewById(R.id.correct);
         CharSequence answer = textview.getText().toString();
         Log.i(LOGTAG, (String) answer);
         if (message == answer) {
                Toast.makeText(getApplicationContext(), "Correct", Toast.LENGTH_LONG).show();
            } else if (message != answer);{
                Toast.makeText(getApplicationContext(), "Incorrect", Toast.LENGTH_LONG).show();
            }

     }

The Log

06-04 18:56:25.752: I/APP(1972): Germany
06-04 18:56:25.752: I/APP(1972): Germany

The button is of course a button and the textview is an invisible textview. As you can see from the LOGCAT both "message" and "answer" give the same text however the answer to the " if message == answer" is always incorrect. Does anyone why and how to fix this. Kind Regards, Derek

nybler42
  • 43
  • 4

2 Answers2

0

Use message.equals(answer). In Java Strings are treated as objects, so == compares reference, not actual string content.

AxiomaticNexus
  • 6,190
  • 3
  • 41
  • 61
0

In Java == compares the references not the contents of the strings. Use message.equals(answer) for content comparison.

Xavier Leclercq
  • 313
  • 2
  • 8