java Android,无效双:“空白”字段使程序崩溃
在用户输入后,我尝试使用按钮进行计算。当我没有填写字段并按下按钮时,我的程序会崩溃,但我只想发送一条消息。。我读过很多其他类似的问题,但我不明白我必须做些什么来修复我的代码。。 有人能帮我吗??谢谢
主要活动。xml:
<EditText
安卓:layout_width="130dp"
安卓:layout_height="wrap_content"
安卓:inputType="numberDecimal"
安卓:ems="10"
安卓:id="@+id/editText1"/>
<EditText
安卓:layout_width="130dp"
安卓:layout_height="wrap_content"
安卓:inputType="numberDecimal"
安卓:ems="10"
安卓:id="@+id/editText2"/>
<EditText
安卓:layout_width="130dp"
安卓:layout_height="wrap_content"
安卓:inputType="numberDecimal"
安卓:ems="10"
安卓:id="@+id/editText3"/>
<TextView
安卓:layout_width="wrap_content"
安卓:layout_height="wrap_content"
安卓:text=""
安卓:id="@+id/textView1"/>
<Button
安卓:layout_width="65dp"
安卓:layout_height="wrap_content"
安卓:id="@+id/calculateButton
安卓:background="@安卓:drawable/ic_menu_edit" />
主要活动。java:
......
mEditText1 = (EditText)findViewById(R.id.editText1);
mEditText2 = (EditText)findViewById(R.id.editText2);
mEditText3 = (EditText)findViewById(R.id.editText3);
mTextView = (TextView)findViewById(R.id.textView1);
cButton = (Button)findViewById(R.id.calculateButton);
cButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//When the button is clicked, call the calucate method.
calculate();
}
});
......
public void calculate(){
Double value1 = Double.parseDouble(mEditText1.getText().toString());
Double value2 = Double.parseDouble(mEditText2.getText().toString());
Double value3 = Double.parseDouble(mEditText3.getText().toString());
if((value1!=0)&&(value2!=0)) {
if ((value1 != null) && (value2 != null) && (value3 != null)) {
calculatedValue = (value2 * value3) / value1;
mTextView.setText(calculatedValue.toString());}
else {
Toast.makeText(getApplicationContext(), "Please fill them all", Toast.LENGTH_LONG).show();
}
}
我得到的错误是:
12-22 20:09:26.694 18523-18523/com.example.nigi.myapplication E/AndroidRuntime: FATAL EXCEPTION: main
java.lang.NumberFormatException: Invalid double: ""
at java.lang.StringToReal.invalidReal(StringToReal.java:63)
at java.lang.StringToReal.parseDouble(StringToReal.java:248)
at java.lang.Double.parseDouble(Double.java:295)
at 安卓.view.View.performClick(View.java:4442)
at 安卓.view.View$PerformClick.run(View.java:18473)
at 安卓.os.Handler.handleCallback(Handler.java:733)
at 安卓.os.Handler.dispatchMessage(Handler.java:95)
at 安卓.os.Looper.loop(Looper.java:136)
at 安卓.app.ActivityThread.main(ActivityThread.java:5105)
谢谢
# 1 楼答案
使用以下代码: