Search code examples
androidandroid-edittextnumberformatexception

numberformatexception and edittext in android


Following code gives me numberformatexception. can you please tell me where to put exepcions or what to do about following lines? logcat tells that there is a problem on commented line

public void zaplatiti(){
   EditText zbrojka = (EditText) findViewById(R.id.editText7);
   Float[] strings = new Float[allTexts.size()];
   Float zbroj=(float) 0;
   for(int i=0; i < allTexts.size(); i++){
       strings[i] = Float.valueOf(allTexts.get(i).getText().toString());////problem


   }
   for (int k=0;k<strings.length;k++){
       zbroj =zbroj+ strings[k];}

   }
   zbrojka.setText(String.valueOf(zbroj)+"KN");

}


Solution

  • for(int i=0; i < allTexts.size(); i++){
        try {
            strings[i] = Float.valueOf(allTexts.get(i).getText().toString());////problem
        }
        catch (NumberFormatException e) {
            // Code to execute if the entered value is not a number
        }
    }
    

    This is also possible to avoid by only allowing your EditTexts to have numerical values. That will force the user to only enter a numerical value in the first place, then you don't have to catch the exception. But then you should check if the entered text is empty first.

    EDIT:

    For doing this you must make an if statement, but the correct comparison beetween String values is:

    if ( mEditText.getText().toString().equals("String to compare with")){ ... } 
    

    the "numerical mode" of an editText could be set up in the XML file as:

    android:inputType = "number"
    

    Other valid numerical modes are numberSigned and numberDecimal.

    So after changing the input type your code could look like:

    for(int i=0; i < allTexts.size(); i++){
        if (!allTexts.get(i).getText().toString().equals("")) {
            strings[i] = Float.valueOf(allTexts.get(i).getText().toString());////problem
        }
        else {
            // Code to execute if there is no entered value
        }
    }