Android:从EditText字段获取数据时获得NumberFormatExxception

时间:2013-01-28 19:10:59

标签: android android-layout android-emulator

java.lang.RuntimeException:无法启动活动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() {

3 个答案:

答案 0 :(得分:0)

似乎输入无效。请检查两次,您不要尝试将字母解析为数字。如果您有浮动,请检查您是否使用正确的语言环境进行解析。例如。在德国是pi 3,1415 ...而不是3.1415 ......

如果你不能预先分析这些值,可以将解析试验放在try catch块中,如下所示:

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

答案 1 :(得分:0)

您所在的onCreate()指定了字段。用户没有时间输入任何有效数据。你需要在其他地方移动数据的提取......就像你的onClick()一样。

答案 2 :(得分:0)

将您的代码从onCerate移动到其他方法 (例如Button的onClick方法) 你应该 试试这个:

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();  
} 

对于每个文本字段,您要阅读的内容 评论: 浮点格式为2.3,不使用2,3