1

I'm trying to check the editText condition. In the code below, I declared a setOnClickListener method to check the condition of editText. If condition is true, I want to print toast message, change the activity and to output a sound. If condition fails, it should toast a single message. In both cases if it's true or not, it prints me only "Incorect" no matter if editText is correct.

What I am doing wrong?

    public void next(View v){

    final MediaPlayer correctSound = MediaPlayer.create(this, R.raw.correctsound);
    Button playCorrectSound = (Button) this.findViewById(R.id.angry_btn1);

    final EditText editTextt = (EditText) findViewById(R.id.editText);

    playCorrectSound.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {

            editTextt.setVisibility(View.INVISIBLE);
            if(editTextt.getText().toString() == "string")
            {
                Toast.makeText(getApplicationContext(), "Correct", Toast.LENGTH_SHORT).show();
                correctSound.start();
                Intent i = new Intent(Hereuu.this, MainActivity.class);
                startActivity(i);
            } else {
                Context context = getApplicationContext();
                CharSequence text = "Incorect";
                int duration = Toast.LENGTH_SHORT;
                Toast toast = Toast.makeText(context, text, duration);
                toast.show();
            }
            editTextt.setVisibility(View.VISIBLE);

        }
    });

}
T. Jony
  • 61
  • 1
  • 9

4 Answers4

0

in java you need to compare strings using equals method instead of == check this topic for more details

Shpytyack Artem
  • 306
  • 2
  • 15
0

I would suggest you to take some basic JAVA lessons. That will immensely help you.

For now, the problem is in the way you are checking equality of the strings. You do not use == with strings, you use String#equals() method. So,

Change

editTextt.getText().toString() == "string"

to

editTextt.getText().toString().equals("string")

zeekhuge
  • 1,594
  • 1
  • 13
  • 23
0

Make sure to compare strings in java with .equals and not ==. Use this if statement:

if(editTextt.getText().toString().equals("string"){
Appafly
  • 656
  • 2
  • 6
  • 24
0

Like everyone had said, you

Basically, when you use == operator, your are checking if the reference for object are the same/equals. When you use .equals(String), the method checks the content.

tip: When your are working with Strings, remember to avoid NullPointerException situations. So,you should write "constant".equals(editTextValue) instead of editTextValue.equals("constant")

The link bellow will help you to understand how String objects and String content work:

Java String.equals versus ==

regards

Franklin Hirata
  • 290
  • 2
  • 12