2013-04-24 102 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

相關問題