0

I have 2 edittext fields where it needs the item name (String) and the quantity (Integer). If user enters nothing on both fields or if even just one field is empty, I want to show a toast saying "please enter item" or "please enter quantity". It creates and error. Here is the snippet below:

 public void onClick(DialogInterface dialog, int id) {

                        String item = itemET.getText().toString();
                        int quantity = Integer.parseInt(quantityET.getText().toString());
                        if(itemET.equals("")){
                            Toast t =Toast.makeText(GroceryList.this, "Please enter item", 5000);
                            t.show();   
                            }
                            if(quantityET.equals("")){
                            Toast t =Toast.makeText(GroceryList.this, "Please enter quantity or enter 0 if none", 5000);
                            t.show();
                            }

And here is the error in logcat:

09-19 10:01:51.766: E/AndroidRuntime(527): FATAL EXCEPTION: main
09-19 10:01:51.766: E/AndroidRuntime(527): java.lang.NumberFormatException: unable to parse '' as integer
09-19 10:01:51.766: E/AndroidRuntime(527):  at java.lang.Integer.parseInt(Integer.java:362)
09-19 10:01:51.766: E/AndroidRuntime(527):  at java.lang.Integer.parseInt(Integer.java:332)
09-19 10:01:51.766: E/AndroidRuntime(527):  at com.mexican.recipes.GroceryList$1$1.onClick(GroceryList.java:60)
09-19 10:01:51.766: E/AndroidRuntime(527):  at com.android.internal.app.AlertController$ButtonHandler.handleMessage(AlertController.java:159)
09-19 10:01:51.766: E/AndroidRuntime(527):  at android.os.Handler.dispatchMessage(Handler.java:99)
 09-19 10:01:51.766: E/AndroidRuntime(527):     at android.os.Looper.loop(Looper.java:123)
 09-19 10:01:51.766: E/AndroidRuntime(527):     at android.app.ActivityThread.main(ActivityThread.java:3683)
 09-19 10:01:51.766: E/AndroidRuntime(527):     at java.lang.reflect.Method.invokeNative(Native Method)
 09-19 10:01:51.766: E/AndroidRuntime(527):     at java.lang.reflect.Method.invoke(Method.java:507)
 09-19 10:01:51.766: E/AndroidRuntime(527):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
 09-19 10:01:51.766: E/AndroidRuntime(527):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
 09-19 10:01:51.766: E/AndroidRuntime(527):     at dalvik.system.NativeStart.main(Native Method)
omi0301
  • 473
  • 2
  • 5
  • 15

6 Answers6

1

There's two seperate problems in this code: calling parseInt on an empty string is going to raise an exception (the error you're seeing), and you're doing a .equals comparison on the EditText object itself, not on the string contained inside. Do the following:

public void onClick(DialogInterface dialog, int id) {

   String itemString = itemET.getText().toString();
   String quantityString = quantityET.getText().toString();
   int quantity;

   if(itemString.equals(""))
   {
      Toast t =Toast.makeText(GroceryList.this, "Please enter item", 5000);
      t.show();   
   }

   if(quantityString.equals("")){
      Toast t =Toast.makeText(GroceryList.this, "Please enter quantity or enter 0 if none", 5000);
      t.show();
   }
   else {
      quantity = Integer.parseInt(quantityString);
   }
}

This will still crash if you supply something which isn't a number (for example, if you typed 'a' into the box), but it should be able to handle nothing being entered.

Xono
  • 1,900
  • 17
  • 20
  • 2
    +1 for clean code, but quantity = Integer.parseInt("a"); will crash the code :) and why Integer.parseInt(quantityString); on the if(quantityString.equals("")) ? :) –  Sep 20 '12 at 02:48
  • Oops got mixed up, too used to writing checks for *not* being an empty string :P Will fix it now – Xono Sep 20 '12 at 02:51
  • 1
    @ Xono, I did use the first code from Lucifer where he declared quantity = 0; That made my app set integer default to 0 if nothing was entered. He deleted that answer. But good enough answer for me.. But upon checking on your code, it is much better since it does show the toasts that I wanted. But it automatically comes out of the alertdialog. Is there anyway that these toast would show while the alertdialog is still there? – omi0301 Sep 20 '12 at 03:08
  • If you make use of a call to `dismiss()` further down in the `onClick` method, just place a `return` call after both lines reading `t.show()` (but still inside the if statements). If you have a `dismiss()` call somewhere else, please post the code that calls it. If you don't have a `dismiss()` method at all, let me know :P – Xono Sep 20 '12 at 03:21
  • @ Xono I do not have dismiss(); – omi0301 Sep 20 '12 at 03:24
  • Bit beyond the scope of a comment then unfortunately; the simplest answer is you need to override the click listener for the individual buttons, rather than the dialog in general (this will then require you to call `dismiss()` as required). These questions expand on the subject a bit: [Custom dialog](http://stackoverflow.com/questions/2620444/android-how-to-prevent-dialog-closed-or-remain-dialog-when-button-is-clicked) | [Custom Listener](http://stackoverflow.com/questions/6142308/android-dialog-keep-dialog-open-when-button-is-pressed) – Xono Sep 20 '12 at 03:36
1

Note that you may use setError("error");

user1882196
  • 129
  • 2
  • 8
0

While creating your EditText declare android:inputType="number" property init to accept only numeric values.

    public void onClick(DialogInterface dialog, int id) 
    {
                String item;
                int quantity;
                if ( itemET != null )
                {
                     item = itemET.getText().toString();
                }

                if ( quantityET != null && quantityET.getText().toString().trim().length() > 0 )
                {
                     quantity = Integer.parseInt(quantityET.getText().toString().trim());  // trim() method added when converting String to Integer
                }
        if(itemET.getText().trim().equals(""))  // Modification done here
        {
            Toast t =Toast.makeText(GroceryList.this, "Please enter item", 5000);
            t.show();   
        }
        if(quantityET.getText().trim().equals(""))  // Modification done here
        {
            Toast t =Toast.makeText(GroceryList.this, "Please enter quantity or enter 0 if none", 5000);
            t.show();
        }
    }
Lucifer
  • 29,392
  • 25
  • 90
  • 143
  • A note on this: the crash he described is caused by calling `parseInt` on empty string `''`. The `int quantity = ...` line should be *inside* the second if statement in order to resolve the crash. Also, any reason the first if statement can't just do `item.trim().equals("")`? – Xono Sep 20 '12 at 02:13
  • @Xono, agree if you read my answer's code i have use trim() method while converting string to integer. – Lucifer Sep 20 '12 at 02:15
  • 1
    How does `trim()` prevent the crash from trying to parse an empty string? – Xono Sep 20 '12 at 02:21
  • no it isn't : if ( quantityET != null ) it is never null, because it is an int, not an object, troooll –  Sep 20 '12 at 02:37
  • @matheszabi, check it again the `&&` part, now I am 100% sure, it is not going to raise any error – Lucifer Sep 20 '12 at 02:39
  • plus: quantity = Integer.parseInt(quantityET.getText().toString().trim()); it will crash always on empty string :)))) –  Sep 20 '12 at 02:39
  • @matheszabi now it won't crash, check the if condition again – Lucifer Sep 20 '12 at 02:40
  • quantityET is the text field, that is not null, the the text can be empty. Integer.parseInt("") will crash it –  Sep 20 '12 at 02:41
  • It will work as it is atm (though messily), as it now checks the length of the string before attempting to parse it. I've posted how I'd deal with it as a new answer if you want to compare. *resigns from discussion* – Xono Sep 20 '12 at 02:47
0

None of above 2 answers are good, because:

String item = itemET.getText().toString();

here you should check the item, if you want, but not on this line is the crash.

int quantity = Integer.parseInt(quantityET.getText().toString());

here is the problem, because quantityET has an empty string and it isn't checked.

There is 2 solution: One is to check the quantityET.getText() to be not null and length > 0 and the second one it is to put the Try-catch for Integer.parseInt(value)

I would combine the 2:

String quantity = quantityET.getText().toString();
if(quantity != null && quantity.length() > 0){
   try{
     int iQuantity = Integer.parseInt(quantityET.getText().toString());
   }catch(NumberFormatException nfe){
      Log.e("your tag", e);
   }
}

Hope it helps.

0

Try something like this:

public void onClick(DialogInterface dialog, int id) {
    int quantity;
    String item;
    if(itemET.getTExt.toString().trim()!="") {
        item = itemET.getText().toString();   
    } else {
        Toast t =Toast.makeText(GroceryList.this, "Please enter item", 5000);
        t.show();   
    }

    if(quantityET.getText().toString().trim()!="") {
        quantity = Integer.parseInt(quantityET.getText().toString().trim());
    } else {
        Toast t =Toast.makeText(GroceryList.this, "Please enter quantity or enter 0 if none", 5000);
        t.show();
}
Nippey
  • 4,708
  • 36
  • 44
wbyPak
  • 1
0
        if(editText.getText().toString().length()==0)
        Toast.makeText(Registration.this, "Plz Enter Your name", Toast.LENGTH_LONG).show();

    else if (editText1.getText().toString().length() == 0)
        Toast.makeText(Registration.this, "plz enter mobile no.", Toast.LENGTH_LONG).show();
    else {
        Intent i = new Intent(getApplicationContext(), MainActivity.class);
        startActivity(i);
        finish();
    }
Kamal Garg
  • 21
  • 1
  • 2
    Why should the OP "try this"? A **good answer** will always have an explanation of what was done and why it was done that way, not only for the OP but for future visitors to SO that may find this question and be reading your answer. – Maximilian Ast Jul 27 '16 at 10:35