skip to Main Content

I’m working on an application with some mathematical problems.
I made a photo in the photoshop and under the image there is an editText and button.
Everything is fine, but when I click the button when editText is empty the application crashes.
I tried examples from other questions, but they did not help me.

public class Start1Activity extends AppCompatActivity {

Button btn;

public void displayResult(String result) {
    Toast.makeText(Start1Activity.this, result, Toast.LENGTH_SHORT).show();
}

public void guess(View view){
    final EditText EditText2 = (EditText) findViewById(R.id.editText2);

    final int guessNumber = Integer.parseInt(EditText2.getText().toString());

    if (guessNumber == 3 ){
        displayResult("That's right! Click once again for next level");
        btn = (Button) findViewById(R.id.bt3);
        btn.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View view){
                if(EditText2.getText().toString().isEmpty()){
                    displayResult("Please enter some number");
                }
                Intent anythingintent=new Intent(Start1Activity.this,Start2Activity.class);
                startActivity(anythingintent);
            }
        });
    }
    else{
        displayResult("Wrong. Try again!");

    }
}

2

Answers


  1. There’s quite a few things going wrong here, but the headline is you’re doing things in the wrong order. You should do all of the checking of your EditText inside the onClick, otherwise the app might throw a NullPointerException. The below code should work for you.

    public void guess(View view){
        final EditText editTextField = (EditText) findViewById(R.id.editTextField);
        btn = (Button) findViewById(R.id.bt3);
    
        final int guessNumber = Integer.parseInt(editTextField.getText().toString());
    
        btn.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View view){
                if(editTextField.getText().toString().isEmpty()) {
                    displayResult("Please enter a number");
                }
                else if (!(guessNumber == 3)) {
                    displayResult("Wrong. Try again!");
                }
                else {
                    displayResult("That's right! Click once again for next level");
                    Intent anythingintent=new Intent(Start1Activity.this,Start2Activity.class);
                    startActivity(anythingintent);
                }
            }
        });
    }
    
    Login or Signup to reply.
  2. In order to avoid NumberFormatException with parseInt(), make sure earlier (not in onClick()) that a value is entered.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search