kaikai kaikai - 24 days ago 12
Java Question

App crashes with empty float edittext

need help on this!
Im trying to make toast for a empty edittext, and turns out keep getting errors with the float.

Please advise

This is the code:

calcBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {


**float bs = Float.parseFloat(basicSalary.getText().toString());**
float tw = Float.parseFloat(totalAllowance.getText().toString());
float mob = String spinTEXT = spinner.getSelectedItem().toString();

if (spinner.getSelectedItem().equals("Select age group")){
Toast.makeText(sghospitalbonuscalculator.this, "Test 123",
Toast.LENGTH_SHORT).show();
}

if (basicSalary.getText().toString().equals("")){
Toast.makeText(sghospitalbonuscalculator.this, "Test 321",
Toast.LENGTH_SHORT).show();
}


This is the error:

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 sg.self.wser.bonuscalc.bonuscalcu$4.onClick(bonuscalcu.java:96)
at android.view.View.performClick(View.java:4756)
at android.view.View$PerformClick.run(View.java:19749)
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:5221)
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:899)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)



The bonuscalc.java:96 is referring to this line of code:

float bs = Float.parseFloat(basicSalary.getText().toString());


As for the toast, i tried to change the .equals("") to .equals(" "), .equals(null) and .isEmpty, but still it wouldnt work.

Please advise!
Thanks a million!

Edited version:

Code:

if (basicSalary.getText().toString().equals(0.0)){
Toast.makeText(sghospitalbonuscalculator.this, "Test 321",
Toast.LENGTH_SHORT).show();
}


Errors shown:

java.lang.NumberFormatException: Invalid float: ""

Answer

You want to test if your input is blank and if so assign the value 0.0

float bs = 0.0f;
if (basicSalary.getText().toString().equals("") == false){
      bs = Float.parseFloat(basicSalary.getText().toString());
}

further down you test this for the Toast

if (basicSalary.getText().toString().equals("")){
         Toast.makeText(sghospitalbonuscalculator.this, "Test 321",
               Toast.LENGTH_SHORT).show();
}

maybe you could change it to

if (bs == 0.0f){
         Toast.makeText(sghospitalbonuscalculator.this, "Test 321",
               Toast.LENGTH_SHORT).show();
}
Comments