2013-04-24 98 views
-2

以下行,没有mather放置在哪里会崩溃我的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> 

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

EDIT--

以下将显示包含举杯:“有些事情是真的错了”

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

邮政logcat的,请 – 2013-04-24 08:11:46

+0

您试图先设置一些文本? – alicanbatur 2013-04-24 08:12:18

+0

你可以在你的logcat上发布错误行吗?你可能会初始化editText1错误。 – wrecker 2013-04-24 08:12:38

回答

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 
} 
+0

我进入//你有一个编码问题;-)部分。随着更新的代码。 – jipje44 2013-04-24 08:23:19

+0

@ jipje44你必须初始化你的'EditText'变量 – 2013-04-24 08:24:33

+0

你必须用['findViewById()']来解决你的控制问题(http://developer.android.com/reference/android/app/Activity.html#findViewById% 28int%29)。我会更新我的代码。 – rekire 2013-04-24 08:24:39

相关问题