2

I am new to android development , i am trying to develop an app where user can keep a few text field empty, However when user doesn't provide any input in the text field app crashes. How do we handle empty text field in android

Following is my code for text Field.

<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 code:

TextView t1 = (TextView)findViewById(R.id.editText1);
a1 = Integer.parseInt(t1.getText().toString());
Ziem
  • 6,579
  • 8
  • 53
  • 86
Tushar Saha
  • 1,978
  • 24
  • 29
  • Use LogCat to examine the Java stack trace associated with your crash: https://stackoverflow.com/questions/23353173/unfortunately-myapp-has-stopped-how-can-i-solve-this – CommonsWare May 25 '15 at 18:35
  • im guessing you do something with the t1.getText(), and it throw an null pointer exception, an im right? – Akariuz May 25 '15 at 18:35
  • This isn't enough code to see why the app is crashing. What else is your Activity doing with the text field? – BSMP May 25 '15 at 18:35
  • @Akariuz i guess u are correct – Tushar Saha May 25 '15 at 19:08

3 Answers3

3

you should cast EditText instead of TextView.

EditText t1 = (EditText)findViewById(R.id.editText1);
NaiveBz
  • 834
  • 2
  • 8
  • 19
1

Ensure if the TextBox is not empty before parsing the value to the int as

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

Else you can get a java.lang.NumberFormatException: for Invalid int: "";

Mithun
  • 2,075
  • 3
  • 19
  • 26
Sanjeet A
  • 5,171
  • 3
  • 23
  • 40
0

Try this:

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 will bring you something always so it can be and string size 0, wich is empty. that will make the parseInt() throw an error because it won find a number in the string. So you have to ask if the length of the string > 0, before the parse.

Akariuz
  • 663
  • 5
  • 9