Getting a NumberFormatException from a numerical EditText field

前端 未结 7 920
长情又很酷
长情又很酷 2021-01-25 12:16

I\'m trying to create a for-loop to add views to a layout. The for-loop is working fine (I tried it with initialized variables) but I need to get an in

7条回答
  •  忘了有多久
    2021-01-25 13:13

    Your EditText initially has an empty String for its value (ie ""). This is obviously not a number, so when you try to call int i = Integer.parseInt(change); it is giving you an error saying as such.

    There are a few ways to fix this, but it basically boils down to either prevent the error by setting an initial value, or detecting an empty string and handling it properly.

    To prevent the error from occurring...

    EditText numSensors = (EditText) findViewById(R.id.num_sensors);
    String change = numSensors.getText().toString();
    if (change.equals("")){ // detect an empty string and set it to "0" instead
        change = "0";
    }
    int i = Integer.parseInt(change);
    

    Or set the initial value as "0" for the EditText, however this also displays the value 0 in the EditText on your interface rather than being empty, so it might not be suitable for all purposes...

    
    

    If you want to detect the error and handle it properly, you would do this...

    EditText numSensors = (EditText) findViewById(R.id.num_sensors);
    String change = numSensors.getText().toString();
    int i = 0; // set it to 0 as the default
    try {
        i = Integer.parseInt(change);
    }
    catch (NumberFormatException e){}
    

    This basically sets the value of i = 0, and will only change it to a different value if the try{} code doesn't give an error.

提交回复
热议问题