Reputation: 1383
Long story short, my basic app has just a textview, 2x edittexts(for minimum, maximum values of random number) and a button. If minimum and maximum values are submitted everything is okay, but when i leave empty app crashes (well of course its supposed to crash), but when i tried adding some if's to avoid this, but it didn't help really. My code fragment where the crash supposed to happen:
int minimumValue = 1;
int maximumValue = 2;
int randomValue = 3;
if(!minimum.getText().toString().equals("")) {
minimumValue = Integer.parseInt(minimum.getText().toString());
}
if(maximum.getText().toString().equals("")) {
maximumValue = Integer.parseInt(maximum.getText().toString());
}
randomValue = minimumValue + (int)(Math.random() * ((maximumValue - minimumValue) + 1));
textview.setText("" + randomValue);
Upvotes: 0
Views: 102
Reputation: 14590
Dont check with empty String..there may be chance for entering more spaces which results you to throw Exception
.
There is a chance of getting NumberFormatException
too when the data is not number..
so Chage your code like this and try
if (minimum.getText().toString().trim().length() > 0) {
try {
minimumValue = Integer.parseInt(minimum.getText().toString());
} catch (NumberFormatException e) {
}
}
if (maximum.getText().toString().trim().length() > 0) {
try {
maximumValue = Integer.parseInt(maximum.getText().toString());
} catch (NumberFormatException e) {
}
}
Upvotes: 2
Reputation: 2815
I think you are missing "!" here:
//if empty
if(maximum.getText().toString().equals("")) {
\\parse empty
maximumValue = Integer.parseInt(maximum.getText().toString());
}
Try with:
\\if empty
if(!maximum.getText().toString().equals("")) {
maximumValue = Integer.parseInt(maximum.getText().toString());
}
Upvotes: 1