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
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.
In order to avoid NumberFormatException with parseInt(), make sure earlier (not in onClick()) that a value is entered.