2

I have an edittext with input type set to number. I want to check if edittext is empty.

 <EditText
   android:id="@+id/noOfTranset"
   android:layout_width="fill_parent"
   android:layout_height="wrap_content"
   android:layout_marginTop="55dp"
   android:layout_marginLeft="20dp"
   android:layout_marginRight="20dp"
   android:hint="Enter number:"
   android:inputType="number"
   android:textColor="@android:color/black"
   android:maxLength="2"/>

Below is the code which I have tried but doesn't checks for empty edittext. What am I missing here? Thanks.

String numTrans = et1.getText().toString();
int transaction = Integer.parseInt(numTrans);



if(numTrans.trim().length() == 0 || numTrans.equals("") || numTrans == null){

// none of the above conditions check for empty edittext

}
artist
  • 6,271
  • 8
  • 25
  • 35

3 Answers3

1

Problem is your trying to convert the empty string to an Integer. Integer.parseInt will throw NumberFormatException when the input text is null or empty.

Change your code to parse string to integer only when the input text is not empty

if(!TextUtils.isEmpty(numTrans)){
      int transaction = Integer.parseInt(numTrans);
      // do your other stuff here
 }
Libin
  • 16,967
  • 7
  • 61
  • 83
  • Nope, still not working. Here is the logcat05-07 18:43:12.174: E/AndroidRuntime(910): FATAL EXCEPTION: main 05-07 18:43:12.174: E/AndroidRuntime(910): java.lang.NumberFormatException: Invalid int: "" 05-07 18:43:12.174: E/AndroidRuntime(910): at java.lang.Integer.invalidInt(Integer.java:138) 05-07 18:43:12.174: E/AndroidRuntime(910): at java.lang.Integer.parseInt(Integer.java:359) 05-07 18:43:12.174: E/AndroidRuntime(910): at java.lang.Integer.parseInt(Integer.java:332) – artist May 08 '14 at 01:12
  • You are correct. After changing the code if(TextUtils.isEmpty(numTrans)){ Toast.makeText(MainActivity.this, "Error! Enter a number", Toast.LENGTH_LONG).show(); return; } if(!TextUtils.isEmpty(numTrans)) transaction = Integer.parseInt(numTrans); } – artist May 08 '14 at 01:34
0

How about something like this?

EditText usernameEditText = (EditText) findViewById(R.id.editUsername);
sUsername = usernameEditText.getText().toString();
if (sUsername.matches("")) {
    Toast.makeText(this, "You did not enter a username", Toast.LENGTH_SHORT).show();
    return;
} 

Taken from: Check if EditText is empty.

Community
  • 1
  • 1
Nick
  • 925
  • 1
  • 8
  • 13
  • Since it is a number edittext, it's expecting a numeric input. Is it possible to check for null value in int? – artist May 08 '14 at 00:45
0

This is very simple you should check by using trim function like:

String numTrans = et1.getText().toString();

if(!numTrans.trim().length() > 0)
{
    int transaction = Integer.parseInt(numTrans);   
    //code here for empty edittext....

}
Zubair Ahmed
  • 2,857
  • 2
  • 27
  • 47