Search code examples
androidonclicklistener

Error while checking user input


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);

        }
    });

}

Solution

  • 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