Reputation: 375
I have a problem with inputting negative int into my EditText, when I do so I get an error 09-12 06:26:42.025: E/AndroidRuntime(18247): java.lang.NumberFormatException: Invalid int: "-"
xml file:
<EditText
android:id="@+id/downAndDistanceStarting"
android:layout_width="180dp"
android:layout_height="match_parent"
android:ems="10"
android:inputType="numberSigned"
android:selectAllOnFocus="true"
android:textSize="@dimen/enterText" >
java code:
end = (EditText) findViewById(R.id.downAndDistanceEnding);
public void afterTextChanged(Editable s) {
int w = Integer.parseInt(end.getText().toString());
}
I'm assuming there is a problem with my textWatcher and it is "sending" my input after every keyboard "press", so when I'm trying to input -12 it sends "-" for "parsening" before I manage to finish, and that's why my app is crashing, am I right? any one knows how to fix it?
Upvotes: 0
Views: 756
Reputation: 11
I faced the same problem. I put a if condition before it is parsing. Like this, So till you enter the second digit it will not parse.
end = (EditText) findViewById(R.id.downAndDistanceEnding);
public void afterTextChanged(Editable s) {
if(!end.getText().toString().equals("-"));
{
int w = Integer.parseInt(end.getText().toString());
} else { //do something }
}
Upvotes: 1
Reputation: 66637
Yes you are correct. Wrap your code in try/catch block, then, when - is received it will throw NumberFormatException and it will be catched.
try
{
int w = Integer.parseInt(end.getText().toString());
}catch(NumberFormatException e)
{
}
Upvotes: 0