Search code examples
androidnumberformatexception

Invalid long:"" Exception


I have 2 edit text fields ETPredictKm(long value) and ETPredictFuelQty(double value). If I insert one value the other gets autogenerated when i click the respective EditText. I am using onFocusListener. My problem is that when i insert the km value to calculate the fuelQty it gets calculated properly. But when i input the fuel qty and click on ETPredictKm I get the invalid long: "" Exception.

Please help me with your suggestions. Thank you.

Here some code:

 try
     {
        predictKm = Long.parseLong(ETPredictKm.getText().toString()); //Get the error here
        predictFuelQty = Double.parseDouble(ETPredictFuelQty.getText().toString());
    }
    catch(NumberFormatException ne)
    {
        ne.printStackTrace();
    }
    if(isChkLastMileage1 ==true || isChkLastMileage5==true||isChkLastMileage10==true)
    {

        if(ETPredictKm.hasFocus())
        {
           if(predictFuelQty!=0)
            {
                  //predictionMileage is double too
              predictKm =(long) (predictionMileage*predictFuelQty);
              ETPredictKm.setText(String.valueOf(predictKm));

            }
        }
      else if(ETPredictFuelQty.hasFocus())
        {
            // This value is calculated properly            
           if(predictKm!=0)
             {
            predictFuelQty =predictKm/predictionMileage;
        ETPredictFuelQty.setText(new DecimalFormat("##.##").format(predictFuelQty)+" Litres");
             }

        }   
    }

Solution

  • Ok, so I got this working by just putting both the parsing statements into different try-catch blocks. Like so :-

    try
            {
                predictKm = Long.parseLong(ETPredictKm.getText().toString().trim());
    
            }
            catch(NumberFormatException ne)
            {
                ne.printStackTrace();
            }
            try
            {
                predictFuelQty = Double.parseDouble(ETPredictFuelQty.getText().toString().trim());
            }
            catch(NumberFormatException ne)
            {
                ne.printStackTrace();
            }