Here is my piece of code where in i am checking edittext input dynamically.
al_e.addTextChangedListener(new TextWatcher() {
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
// TODO Auto-generated method stub
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
// TODO Auto-generated method stub
}
@Override
public void afterTextChanged(Editable s) {
// TODO Auto-generated method stub
String al_s=s.toString().trim();
if((Float.parseFloat(al_s)<15)|(Float.parseFloat(al_s)>50)|al_s.equals("")){
invalid=1;
al_s="";
//Toast.makeText(getApplicationContext(),"Please enter a valid input\nRange [15mm,50mm]", Toast.LENGTH_SHORT).show();
al_e.setError("Please enter a valid input\nRange [15mm,50mm]");
}else{
al=Float.parseFloat(al_s);
}
}
});
but when i input text in edittext and use backspace to clear the number i get the following exception
02-10 09:43:37.186: E/AndroidRuntime(434): FATAL EXCEPTION: main
02-10 09:43:37.186: E/AndroidRuntime(434): java.lang.NumberFormatException:
02-10 09:43:37.186: E/AndroidRuntime(434): at org.apache.harmony.luni.util.FloatingPointParser.parseFloat(FloatingPointParser.java:305)
02-10 09:43:37.186: E/AndroidRuntime(434): at java.lang.Float.parseFloat(Float.java:323)
02-10 09:43:37.186: E/AndroidRuntime(434): at com.example.iolcalci.Second$4.onTextChanged(Second.java:208)
Searched the forum for similar problem but dint find it. Any help regarding this.I'm a beginner in android development
You can't use parseFloat on an empty string. That is why you are getting a NumberFormatException.
Do something like the following instead.
try {
float num = Float.parseFloat(al_s);
if (num < 15 || num > 50) {
// set invalid...
} else {
al = num;
}
} catch (NumberFormatException e) {
// set invalid...
}
Note also that even though your doing al_s.equals("")
to check for an empty string, it needs to be the first test of the conditional rather than the last. Otherwise the string will be parsed before the test, causing the NumberFormatException
.