-2

以下行,无论放在哪里都会使我的 Android 程序崩溃。

EditText editText1;
double pro = Double.parseDouble(editText1.getText().toString());

附加代码:

 <EditText
        android:id="@+id/editText1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_below="@+id/btsub"
        android:layout_marginTop="58dp"
        android:ems="10"
        android:inputType="number" >

        <requestFocus />
    </EditText>

我究竟做错了什么?我没有调试经验。

编辑 -

下面将显示一个包含:“Something is real wrong”的吐司

try {
                    if(editText1 != null) {
                        pro = Double.parseDouble(editText1.getText().toString());
                    } else {
                        Context context = getApplicationContext();
                        CharSequence text = "Something real wrong";
                        int duration = Toast.LENGTH_SHORT;

                        Toast toast = Toast.makeText(context, text, duration);
                        toast.show();
                    }
                } catch(NumberFormatException e) {
                    Context context = getApplicationContext();
                    CharSequence text = "Empty";
                    int duration = Toast.LENGTH_SHORT;

                    Toast toast = Toast.makeText(context, text, duration);
                    toast.show();
                }
4

1 回答 1

1

首先,您应该检查是否editText1null(这是您的实际问题!*),而不是检查是否NumberFormatException抛出了 a。

*)您的问题是您刚刚定义了对控件的未初始化引用。您需要获得该findViewById()功能的参考:

EditText editText1 = (EditText)findViewById(R.id.editText1);
double pro;
try {
    if(editText1 != null) {
        pro = Double.parseDouble(editText1.getText().toString());
    } else {
        // you have an coding problem ;-)
        // this should now just happen if you change the id in your xml
    }
} catch(NumberFormatException e) {
    // input was no number or an empty string
}
于 2013-04-24T08:16:10.180 回答