Android:Got NumberFormatExxception while getting d

2019-09-22 01:47发布

问题:

java.lang.RuntimeException: Unable to start activity ComponentInfo { com.project/com.project.simple} : java.lang.NumberFormatException

EditText et1,et2,et3;
Button b1, b2;
Float two,three,four;   
@Override
protected void onCreate(Bundle savedInstanceState) {

// TODO Auto-generated method stub

super.onCreate(savedInstanceState);

setContentView(R.layout.can);

et1 = (EditText) findViewById(R.id.editText1);

two = Float.valueOf(et1.getText().toString());

et2 = (EditText) findViewById(R.id.editText2);

three = Float.valueOf(et2.getText().toString());

et3 = (EditText) findViewById(R.id.editText3);

four = Float.valueOf(et3.getText().toString());

    b1 = (Button) findViewById(R.id.button1);

b2 = (Button) findViewById(R.id.button2);

b1.setOnClickListener(new OnClickListener() {

回答1:

you are in onCreate() where the fields are specified. the user could not have time to enter any valid data. you need to move the fetching of the data somewhere else...like your onClick() perhaps.



回答2:

move your code from onCerate to an other method (for example the onClick method of the Button ) and you should try this:

try{
   two = Float.parseFloat(et1.getText().toString());
}catch(NumberFormatException e){
   two = 0;       
   Toast toast = Toast.makeText(this, 'Invalid number format on `two` field', 500);
   toast.show();  
} 

For each text fields what you want to read Comment: float format is 2.3 and don't use 2,3



回答3:

It seems that the input is not valid. Please check twice that you don't try to parse a letters to a number. If you have a float please check that you use the right locale for parsing. E.g. in germany is pi 3,1415... and not 3.1415...

If you cannot preparse the values you could put the parsing trys in try catch blocks like this:

float value;
try {
    value=Float.parseFloat(someString);
} catch(NumberFormatException e) {
    // input was no valid float
}