Getting A Numberformatexception From A Numerical Edittext Field
Solution 1:
Your EditText
initially has an empty String
for its value (ie ""
). This is obviously not a number, so when you try to call int i = Integer.parseInt(change);
it is giving you an error saying as such.
There are a few ways to fix this, but it basically boils down to either prevent the error by setting an initial value, or detecting an empty string and handling it properly.
To prevent the error from occurring...
EditTextnumSensors= (EditText) findViewById(R.id.num_sensors);
Stringchange= numSensors.getText().toString();
if (change.equals("")){ // detect an empty string and set it to "0" instead
change = "0";
}
inti= Integer.parseInt(change);
Or set the initial value as "0"
for the EditText
, however this also displays the value 0
in the EditText
on your interface rather than being empty, so it might not be suitable for all purposes...
<EditText android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="number"
android:text="0"
android:id="@+id/num_sensors" />
If you want to detect the error and handle it properly, you would do this...
EditTextnumSensors= (EditText) findViewById(R.id.num_sensors);
Stringchange= numSensors.getText().toString();
inti=0; // set it to 0 as the defaulttry {
i = Integer.parseInt(change);
}
catch (NumberFormatException e){}
This basically sets the value of i = 0
, and will only change it to a different value if the try{}
code doesn't give an error.
Solution 2:
If you try to parse empty string it will always throw NumberFormatException
.
Change your code to following.
int i;
String change = numSensors.getText().toString();
if(change.length>0)
{
i = Integer.parseInt(change);
}
else
{
i=0;
}
Solution 3:
I think initial Edit text will be empty so "" (blank is not a valid input
) is thowing error you should fill the data in Edit text and then on click on any event you should do the parsing work....
Solution 4:
You are getting this error because there is nothing or a ""
/Empty String initially in your edit text. It makes no sense to get the text of an edit text when it is still being display. You may probably want to have a button or some other event which will signify that the user is done with inputting the value in the edit text and then you can go ahead and get the value of the edit text. But always have a check for the Empty String
Solution 5:
bez you are passing empty String in parseInt() so check before parsing string to int as:
EditTextnumSensors= (EditText) findViewById(R.id.num_sensors);
Stringchange= numSensors.getText().toString();
if (change.trim().equals("")) {
//DO SOMETHING HERE
}
else
{
inti= Integer.parseInt(change);
YOUR CODE HERE....
}
Post a Comment for "Getting A Numberformatexception From A Numerical Edittext Field"