为什么以下行会导致我的Android应用崩溃?

时间:2013-04-24 08:09:55

标签: java android

以下一行,不会放在哪里会导致我的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>

我做错了什么?我没有经历过调试。

编辑 -

以下将显示一个包含“正确的错误”的祝酒词

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

1 个答案:

答案 0 :(得分:1)

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

*)您的问题是您刚刚为控件定义了未初始化的引用。您需要使用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
}