Java.lang.NumberFormatException: Invalid int: "" in android

I already know what causes this error, I just don’t know how to handle the case when the user doesn’t enter anything into the dialog box, and then click the button that parses the string into int. It cannot parse an empty string into int, so it throws an error. I did some research on how to do this, but did not find a satisfactory result that works.

Problem: how do you check if there is text in the dialog box before it tries to run the rest of the code.

+7
source share
4 answers

Some code will help with the syntax, but mostly

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; } 

Alternatively, you can surround with try/catch and catch a numberFormatException, and then print the corresponding message

+10
source

Problem: how do you check if there is text in the dialog box before it tries to run the rest of the code.

Solution: if .

  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 save the extra dependency, I would pull out Common Lang StringUtils to use StringUtils.isBlank instead of trim / isEmpty, because it also handles Unicode.

+1
source
  String text = editText.getText().toString(); if(!text.equals("") && text.matches("^\\d+$")){ cast to int } 
+1
source

The same error caused my application to crash. Ans Simple. Put the code in

try {}

and

catch()

The block that throws the exception, for example, this snapshot of code. 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); } } 
0
source

All Articles