Exorcist
Exorcist

Reputation: 252

NumberFormatException Error

the code is:

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 the logcat error is:

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

Upvotes: 4

Views: 16439

Answers (5)

doom4s
doom4s

Reputation: 141

to me the best way is 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 also add this line to your xml for editText2

android:inputType="numberDecimal"

Hope it helps !

Upvotes: 1

Anonsage
Anonsage

Reputation: 8320

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

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

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

Update: Since you are using EditText, the simplest way to avoid the NumberFormatException is to specify the inputType attribute so that it will only accept numbers. XML example: android:inputType="number". Though, you may still get a value larger (or smaller) that the data type can't hold.

Then, depending on your use case, you could even step up a level by using a custom "IntEditText" or custom InputFilter so that you can specify a min and max, and re-use the code across apps.

Upvotes: 4

Ajinkya
Ajinkya

Reputation: 22710

IMHO you are entering some non float value which is causing this error.

Upvotes: 0

Jarle Hansen
Jarle Hansen

Reputation: 1993

Probably a good idea to validate the value you are reading from editText2 before parsing it to float. Make sure it is a valid number first.

Upvotes: 0

MByD
MByD

Reputation: 137272

Seems like the String in editText2 is empty, so it fails to parse it as float.

A possible solution is to check if the String is empty first, and then decide about default value, another is to catch the exception:

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

Upvotes: 9

Related Questions