java.lang.NumberFormatException: Invalid int: "" in android
Asked Answered
E

4

8

I already know what is causing this error, I just do not know how to handle the case when a user doesn't enter anything into the dialogue box, then hit the button which parses the string into an int. It can't parse an empty string into an int, so it throws an error. I have done some research on how to do this, but have not found a satisfactory result that works.

Problem: How do you check to see if the dialogue box has text in it, before it tries to run the rest of the code.

Elizabetelizabeth answered 24/5, 2013 at 1:33 Comment(0)
S
12

Some code would help with the syntax but basically

 if ("".equals(text)  // where text is the text that you get from an EditText or wherever you get it
 {    // give message to enter valid text;    }

Also, you can surround with a try/catch and catch a numberFormatException then print an appropriate message

Sf answered 24/5, 2013 at 1:36 Comment(0)
D
1

Problem: How do you check to see if the dialogue box has text in it, before it tries to run the rest of the code.

Solution: An if statement.

 int parseToInt(String maybeInt, int defaultValue){
     if (maybeInt == null) return defaultValue;
     maybeInt = maybeInt.trim();
     if (maybeInt.isEmpty()) return defaultValue;
     return Integer.parseInt(maybeInt);
 }

If you can spare the extra dependency, I'd pull in Common Lang StringUtils, to use StringUtils.isBlank instead of trim/isEmpty, because that also handles Unicode.

Deka answered 24/5, 2013 at 1:35 Comment(0)
S
1
   String text = editText.getText().toString(); 
   if(!text.equals("") && text.matches("^\\d+$")){
       cast to int
    }
Stoffel answered 24/5, 2013 at 1:47 Comment(0)
V
0

The Same Error Was Causing My Application To Crash. Ans is Simple- Put the code in the

try{ }

and

catch()

Block which causes Exception ,like this code snip.This Works for me.

public void setAge(String age) {

    final Calendar c = Calendar.getInstance();
    int yearCurrent = c.get(Calendar.YEAR);
    try {
        int yearPrev = (int) Integer.parseInt(age.substring(0, 4));//this line was causing the error
        int ageYear=yearCurrent-yearPrev;
        ageUser="Age : "+Integer.toString(ageYear);
    }
    catch(NumberFormatException numberEx) {
        System.out.print(numberEx);
    }


}
Vescuso answered 14/11, 2015 at 6:53 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.