Search code examples
androidandroid-edittextnumberformatexception

Why is this code throwing NumberFormatException Invalid int: ""?


I'm trying to get it to if a user doesn't enter a value in the EditText boxes, the initial value is set to 0 (to prevent the crash error NumberFormatException Invalid int: "") which is thrown assuming because there is no integer value to read, since the user didn't input one in this case.

I've tried a number of things most recently this:

String boozeAmount = boozeConsumed.getText().toString();

        if (boozeAmount == "" || boozeAmount == null){
            boozeConsumed.setText("0");
            boozeAmount = boozeConsumed.getText().toString();
        }
        int boozeOz = Integer.parseInt(boozeAmount) * 12;
        double beerCalc = boozeOz * 4 * 0.075;

But it seems to still throw the same error, not sure why the int values aren't being set to 0?

Throwing error on

int boozeOz = Integer.parseInt(boozeAmount) * 12;

Solution

  • if (boozeAmount == "" || boozeAmount == null){
    

    It can be easily deduced from your explanation that this particular if statement is returning true, that's why your string value is not being set to "0".

    Strings in Java are not primitive, i.e they cannot be compared with the comparator ==. You need to use the method equals to compare strings, as in boozeAmount.equals("").

    Apache Commons has a StringUtils utility that can check if strings are null or empty. Check out isEmpty and isBlank.