Error NumberFormatException

the code:

editText2=(EditText) findViewById(R.id.editText2); editText3=(EditText) findViewById(R.id.editText3); float from_value= Float.parseFloat(editText2.getText().toString()); editText3.setText(" "+(from_value * 100.0)); 

And logcat error:

03-18 03: 19: 07.847: E / AndroidRuntime (875): thrown: java.lang.NumberFormatException: Invalid float: ""

+4
source share
5 answers

It looks like the line in editText2 is empty, so it cannot parse it as a float.

A possible solution is to check if the line is first empty, and then decide on the default value, the other is to catch the exception:

 float from_value; try { from_value = Float.parseFloat(editText2.getText().toString()); } catch(NumberFormatException ex) { from_value = 0.0; // default ?? } 
+7
source

You should try to avoid using try / catch, if at all possible, because this is not the preferred method.

The correct way to avoid this error is to stop it before it occurs.

 if (mEditText.getText().toString().equals("")) { value = 0f; } else { value = Float.parseFloat(mEditText.getText().toString()); } 

Update. Since you are using EditText , the easiest way to avoid a NumberFormatException is to specify the inputType attribute to accept only numbers. XML example: android:inputType="number" . However, you can still get a larger (or smaller) value that the data type cannot store.

Then, depending on your use case, you can even level up using a custom "IntEditText" or custom InputFilter so you can specify a minimum and maximum number and reuse the code in applications.

+4
source

for me the best way to do it like this:

 editText2=(EditText) findViewById(R.id.editText2); editText3=(EditText) findViewById(R.id.editText3); if(!editText2.getText().toString().matches("")){ float from_value= Float.parseFloat(editText2.getText().toString()); editText3.setText(" "+(from_value * 100.0)); } 

And add this line to your xml for editText2

 android:inputType="numberDecimal" 

Hope this helps!

+1
source

It is probably a good idea to check the value you read from editText2 before parsing it into a float. First of all, make sure that this is a valid number.

0
source

IMHO you enter some non float value that causes this error.

0
source

Source: https://habr.com/ru/post/1402024/


All Articles