Java Simple Number Game App Crashes When Edittext Is Empty
Solution 1:
Before you try to use text from EditText
, check if it contains any text or not. If it does, read the text otherwise display a toast
Stringtext= editTextGuess.getText().toString().trim();
if(text.length == 0) {
// show toast
} else {
// use text from editTextGuess
}
Solution 2:
Check your edit text string value before assigning it to the variable.
publicvoidguess(View view){
Log.i("Button clicked", "Worked!");
int guessValue;
if(!editTextGuess.getText().toString().equals("")){
guessValue = Integer.parseInt(editTextGuess.getText().toString());
Log.i("Entered Value:", Integer.toString(guessValue));
Log.i("The random number is:", Integer.toString(RandomNumber));
String message;
if(guessValue > RandomNumber){
message = "Your guessed number is too high!";
} elseif(guessValue < RandomNumber){
message = "Your guessed number is too low!";
} elseif(guessValue == RandomNumber){
message = "You were right! Let's play again!";
generateRandomNumber();
Log.i("Info", "New random number created");
} else {
message = "Something went wrong...";
}
Toast.makeText(this, message, Toast.LENGTH_LONG).show();
} else {
Toast.makeText(this, "Oops, your Textfield is empty", Toast.LENGTH_LONG).show();
}
}
Solution 3:
It crashes because parseInt()
throws a NumberFormatException
when it tries to parse an empty string.
How to fix this depends on what you want if the input field is empty.
String value = editTextGuess.getText().toString();
if (!value.isEmpty()) {
guessValue = Integer.parseInt(value);
...
}
else {
Toast.makeText(this, "Oops, input field is empty", ...);
}
Solution 4:
As the issue has already been pointed out by @Yousaf this answer that will help you move forward but would like to add few things to take care in future to help debugging easier: Always try to create multiple statements where you are dereferencing object like
guessValue = Integer.parseInt(editTextGuess.getText().toString());
can be written as
Stringtext=editTextGuess.getText().toString();
guessValue = Integer.parseInt(text);
It will help you know the exact cause of failure.Like you may encounter NumberFormatException
if the entered string is not number.
Post a Comment for "Java Simple Number Game App Crashes When Edittext Is Empty"