I have a button and an edittext. The user enters a number and then clicks the button. Something then happens with that number.
However i get an error when the edittext is blank. How do i fix this? My code below is my attempt..but it doesn’t work as i get the following error and my app closes:
E/AndroidRuntime(324): java.lang.NumberFormatException: unable to parse ” as integer
public void onClick(View arg0) {
// TODO Auto-generated method stub
switch (arg0.getId()) {
case R.id.bBankDeposit:
deposit();
break;
case R.id.bBankWithdraw:
withdraw();
break;
}
}
public void deposit() {
String d = etDepositAmount.getText().toString();
Integer depositAmount = Integer.valueOf(d);
if (depositAmount > playerCash | depositAmount <= 0
| etDepositAmount.getText().toString() == "") {
new AlertDialog.Builder(this).setTitle("Wait")
.setMessage("Please enter a valid deposit value.")
.setPositiveButton("OK", null).show();
etDepositAmount.setText("");
} else {
int newBankBalance = playerBalance + depositAmount;
playerBalance = newBankBalance;
playerCash = (playerCash - depositAmount);
bankBalance.setText("Bank Balance: $" + playerBalance);
cash.setText("Cash in hand: $" + playerCash);
etDepositAmount.setText("");
Player stats = new Player(this);
stats.open();
stats.bankDeposit(playerId, playerCash, playerBalance);
stats.close();
}
}
}
The idea behind your solution is correct, you just have some minor syntax errors.
When you do
Integer.valueOf(string)you need to handle a number format exception. It’s just Java’s way of letting you know it can reliably return an Integer for the given string.|is a bitwise OR operation. Presumably you want||, which compares using boolean logic. Secondly, when comparing strings you want to compare by value, not by reference.==compares by reference, whilesomeString.equals(someOtherString)will actually check the contents of the string. You really don’t need to do that though because you’ve already parsed it into an Integer.With those fixes you’ll figure out if the input is incorrect and display an alert if necessary.
So – the full solution is ….