【问题标题】:Android:Got NumberFormatExxception while getting data from EditText fieldAndroid:从 EditText 字段获取数据时获取 NumberFormatException
【发布时间】:2013-01-12 05:20:42
【问题描述】:

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() {

【问题讨论】:

    标签: android android-layout android-emulator


    【解决方案1】:

    您位于指定字段的onCreate() 中。用户没有时间输入任何有效数据。您需要将数据的获取移到其他地方……也许就像您的onClick()

    【讨论】:

      【解决方案2】:

      将您的代码从 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();  
      } 
      

      对于您要阅读的每个文本字段 评论: float 格式是 2.3,不要使用 2,3

      【讨论】:

        【解决方案3】:

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

        如果您无法预解析这些值,您可以将解析尝试放在 try catch 块中,如下所示:

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

        【讨论】:

        • 未输入任何输入...在此项目中从外部获取值。
        • 在这种情况下,将 Float.valueOf() 语句放在 try catch 块中
        猜你喜欢
        • 2011-01-30
        • 2012-05-17
        • 2014-05-31
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-06-30
        相关资源
        最近更新 更多