2015-05-25 34 views
2

我是新來的android開發,我試圖開發一個應用程序,其中用戶可以保留一些文本字段爲空, 但是,當用戶沒有在文本字段應用程序崩潰提供任何輸入。 我們如何處理android中的空文本字段如何在Android中保持文本字段爲空?

以下是我對文本字段的代碼。

<EditText 
    android:layout_width="40dp" 
    android:layout_height="40dp" 
    android:inputType="number" 
    android:ems="10" 
    android:id="@+id/editText1" 
    android:layout_weight="1" 
    android:background="#ffb7ffbf"/>` 

java代碼:

TextView t1 = (TextView)findViewById(R.id.editText1); 
a1 = Integer.parseInt(t1.getText().toString()); 
+0

使用LogCat檢查與您的崩潰相關的Java堆棧跟蹤:https://stackoverflow.com/questions/23353173/uncomfort-myapp-has-stopped-how-can-i-solve-this – CommonsWare

+0

即時猜測你做一些與t1.getText(),它拋出一個空指針異常,即時通訊權利? – Akariuz

+0

這不足以查看應用程序崩潰的原因。你的活動還有什麼與文本字段? – BSMP

回答

1

確保如果TextBox是不是值解析到int

if (e.length()>0) { 
    int a1= Integer.parseInt(e.getText().toString()); 
} 

否則,你可以得到一個java.lang.NumberFormatException: for Invalid int: "";

+0

謝謝...這工作 –

3

你應該投,而不是TextView的EditText上。

EditText t1 = (EditText)findViewById(R.id.editText1); 
+0

沒有它沒有幫助 –

+3

@NaiveBz公共類EditText擴展TextView'所以它不應該是一個問題 – Mithun

0

當您嘗試a1= Integer.parseInt(t1.getText().toString());也有一些地方,你可以得到NPE

  1. t1.getText()可能是null如果說t1.getText().toString()返回一定的價值,因此.toString()null對象會拋出NPE
  2. ,但不是一個數字或周圍有「23」的號碼一些空間,然後它會導致在NumberFormatException。你可以檢查
String s=t1.getText().toString(); 
if(s!=null)s=s.trim(); 
0

嘗試此之前空:

TextView t1=(TextView)findViewById(R.id.editText1); 

String aux = t1.getText.toString(); 

if(aux.length() > 0) 
    a1= Integer.parseInt(aux); 
else 
// the text is empty 

getText.toString會給你帶來一些東西,所以它可以和字符串大小0,這是空的。這將使parseInt()拋出一個錯誤,因爲它贏得了在字符串中找到一個數字。 所以你必須要問一下,在解析之前,如果字符串長度> 0。