按钮单击,崩溃

时间:2014-05-16 21:51:40

标签: java android

每次点击我的按钮,我的应用程序都会崩溃。我试过Toast文本但它仍然崩溃。我也已经完成了我的代码和按钮的工作。这里有什么问题

final EditText Number1 =(EditText)findViewById(R.id.editText);
final EditText Number2 =(EditText)findViewById(R.id.editText2); //LINE 29
Button Add =(Button)findViewById(R.id.button);
final TextView Output = (TextView)findViewById(R.id.textView);

Add.setOnClickListener(new View.OnClickListener() {
@Override
 public void onClick(View v) {
  int myNum1 = Integer.parseInt(Number1.getText().toString());
  int myNum2 = Integer.parseInt(Number2.getText().toString());
  Output.setText(Integer.toString(myNum1));
}
});

收到错误。

05-16 17:50:35.912    1995-1995/com.example.addnumber.app E/AndroidRuntime﹕ FATAL EXCEPTION: main
    Process: com.example.addnumber.app, PID: 1995
    java.lang.NumberFormatException: Invalid int: ""
            at java.lang.Integer.invalidInt(Integer.java:137)
            at java.lang.Integer.parseInt(Integer.java:358)
            at java.lang.Integer.parseInt(Integer.java:331)
            at com.example.addnumber.app.MainActivity$1.onClick(MainActivity.java:29)
            at android.view.View.performClick(View.java:4633)
            at android.view.View$PerformClick.run(View.java:19330)
            at android.os.Handler.handleCallback(Handler.java:733)
            at android.os.Handler.dispatchMessage(Handler.java:95)
            at android.os.Looper.loop(Looper.java:157)
            at android.app.ActivityThread.main(ActivityThread.java:5356)
            at java.lang.reflect.Method.invokeNative(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:515)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1265)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1081)
            at dalvik.system.NativeStart.main(Native Method)

1 个答案:

答案 0 :(得分:1)

空字符串发出错误

java.lang.NumberFormatException: Invalid int: ""

因此,您应该尝试检查text值是否具有int

的正确值
if (!Number1.getText().toString().isEmpty())
    int myNum1 = Integer.parseInt(Number1.getText().toString());