-3

I am trying to check if the EidtText is empty or not. Variable for EditText is in float type.

float interObtain = Float.valueOf(editText1.getText().toString());
if (interObtain == 0 ) {
  editText1.setError("Please Fill this Field");
}

07-31 12:04:16.363 26780-26780/com.example.iubmeritcalculator E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.iubmeritcalculator, PID: 26780
java.lang.NumberFormatException: Invalid float: ""at java.lang.StringToReal.invalidReal(StringToReal.java:63) at java.lang.StringToReal.parseFloat(StringToReal.java:308) at java.lang.Float.parseFloat(Float.java:306) at java.lang.Float.valueOf(Float.java:343) at android.view.View.performClick(View.java:5052)at android.view.View$PerformClick.run(View.java:20162) at android.os.Handler.handleCallback(Handler.java:739)at android.os.Handler.dispatchMessage(Handler.java:95) at android.os.Looper.loop(Looper.java:135) at android.app.ActivityThread.main(ActivityThread.java:5753) at java.lang.reflect.Method.invoke(Native Method) at java.lang.reflect.Method.invoke(Method.java:372) at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:145) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1200)
Phantômaxx
  • 37,901
  • 21
  • 84
  • 115
  • 1
    *java.lang.NumberFormatException: Invalid double: ""* Isn`t this message clear? if the field is empty you get an empty string which is not a souble – Jens Jul 31 '19 at 07:01

3 Answers3

2

You're trying to parse an empty string into a Float, which fails.

If you want to check for an empty value, 0 value or invalid formatted values you could try:

   if (editText1.getText().isEmpty()) {
     editText1.setError("Please Fill this Field");
   } else {
     try{
       float interObtain = Float.valueOf(editText1.getText());
       if (interObtain == 0 ) {
         editText1.setError("Value should be different from 0");
       }
     } catch(NumberFormatException ex){
       editText1.setError("Value has an invalid format");
     }
   }
TheWhiteRabbit
  • 1,253
  • 1
  • 5
  • 18
0
private boolean isEditTextEmpty(EditText editText) {
    return editText.getText().toString().trim().length() == 0;
}

This is a method you could implement which returns true, if the editText is empty, it`s better than checking the float value.

Alan
  • 589
  • 5
  • 29
0

editText1.getText().toString() is return "" value when edittext is empty or it can't converted in float number so it's giveing error

you can check with this code

if(editText1.getText().toString().equalsIgnoreCase(""){
// show your error here
}
Ganesh
  • 50
  • 9