9

If the user left the edittext empty an error occurs java.lang.NumberFormatException: Invalid int: "". The error comes at line

 if (a=="" && b=="")

and also at line

 int result = Integer.parseInt(a) + Integer.parseInt(b);
 t1.setText(Integer.toString(result));

Calci.java

package com.example.calculator;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

public class Calci extends Activity {
    TextView t1;
    EditText e1, e2;
    Button add, sub, mul, div;
    Context c=this;

    String b, a;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_calci);
        e1 = (EditText) findViewById(R.id.EditText01);
        e2 = (EditText) findViewById(R.id.EditText02);
        add = (Button) findViewById(R.id.add);
        sub = (Button) findViewById(R.id.sub);
        mul = (Button) findViewById(R.id.mul);
        div = (Button) findViewById(R.id.div);
        t1 = (TextView) findViewById(R.id.textView1);
        a = e1.getText().toString();
        b = e2.getText().toString();
add.setOnClickListener(new View.OnClickListener() {

    @Override
    public void onClick(View arg0) {
        if (a=="" && b==""){
                AlertDialog.Builder a1 = new AlertDialog.Builder(c);


                // Setting Dialog Title
                a1.setTitle("Alert Dialog");

                // Setting Dialog Message
                a1.setMessage("PLEASE ENTER SOMETHING");

                a1.setPositiveButton("yes",
                        new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog,
                                    int button1) {
                                // if this button is clicked, close
                                // current activity
                                dialog.cancel();
                            }

                        });

                // Showing Alert Message
                AlertDialog alertDialog = a1.create();
                a1.show();

            }

        else{
            int result = Integer.parseInt(a) + Integer.parseInt(b);
            t1.setText(Integer.toString(result));
            InputMethodManager imm = (InputMethodManager)getSystemService(
                      Context.INPUT_METHOD_SERVICE);
                imm.hideSoftInputFromWindow(add.getWindowToken(), 0);
        }

    }

});
    }
}

LogCat:

03-19 15:42:21.165: E/Trace(25381): error opening trace file: Permission denied (13)
03-19 15:42:21.165: D/ActivityThread(25381): setTargetHeapUtilization:0.25
03-19 15:42:21.165: D/ActivityThread(25381): setTargetHeapIdealFree:8388608
03-19 15:42:21.165: D/ActivityThread(25381): setTargetHeapConcurrentStart:2097152
03-19 15:42:21.385: D/libEGL(25381): loaded /system/lib/egl/libEGL_adreno200.so
03-19 15:42:21.465: D/libEGL(25381): loaded /system/lib/egl/libGLESv1_CM_adreno200.so
03-19 15:42:21.475: D/libEGL(25381): loaded /system/lib/egl/libGLESv2_adreno200.so
03-19 15:42:21.475: I/Adreno200-EGL(25381): <qeglDrvAPI_eglInitialize:299>: EGL 1.4 QUALCOMM build:  (Merge)
03-19 15:42:21.475: I/Adreno200-EGL(25381): Build Date: 07/09/13 Tue
03-19 15:42:21.475: I/Adreno200-EGL(25381): Local Branch: AU_41
03-19 15:42:21.475: I/Adreno200-EGL(25381): Remote Branch: 
03-19 15:42:21.475: I/Adreno200-EGL(25381): Local Patches: 
03-19 15:42:21.475: I/Adreno200-EGL(25381): Reconstruct Branch: 
03-19 15:42:21.675: D/OpenGLRenderer(25381): Enabling debug mode 0
03-19 15:42:24.325: D/AndroidRuntime(25381): Shutting down VM
03-19 15:42:24.325: W/dalvikvm(25381): threadid=1: thread exiting with uncaught exception (group=0x41972378)
03-19 15:42:24.395: E/AndroidRuntime(25381): FATAL EXCEPTION: main
03-19 15:42:24.395: E/AndroidRuntime(25381): java.lang.NumberFormatException: Invalid int: ""
03-19 15:42:24.395: E/AndroidRuntime(25381):    at java.lang.Integer.invalidInt(Integer.java:138)
03-19 15:42:24.395: E/AndroidRuntime(25381):    at java.lang.Integer.parseInt(Integer.java:359)
03-19 15:42:24.395: E/AndroidRuntime(25381):    at java.lang.Integer.parseInt(Integer.java:332)
03-19 15:42:24.395: E/AndroidRuntime(25381):    at com.example.calculator.Calci$1.onClick(Calci.java:67)
03-19 15:42:24.395: E/AndroidRuntime(25381):    at android.view.View.performClick(View.java:4147)
03-19 15:42:24.395: E/AndroidRuntime(25381):    at android.view.View$PerformClick.run(View.java:17161)
03-19 15:42:24.395: E/AndroidRuntime(25381):    at android.os.Handler.handleCallback(Handler.java:615)
03-19 15:42:24.395: E/AndroidRuntime(25381):    at android.os.Handler.dispatchMessage(Handler.java:92)
03-19 15:42:24.395: E/AndroidRuntime(25381):    at android.os.Looper.loop(Looper.java:213)
03-19 15:42:24.395: E/AndroidRuntime(25381):    at android.app.ActivityThread.main(ActivityThread.java:4787)
03-19 15:42:24.395: E/AndroidRuntime(25381):    at java.lang.reflect.Method.invokeNative(Native Method)
03-19 15:42:24.395: E/AndroidRuntime(25381):    at java.lang.reflect.Method.invoke(Method.java:511)
03-19 15:42:24.395: E/AndroidRuntime(25381):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:789)
03-19 15:42:24.395: E/AndroidRuntime(25381):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:556)
03-19 15:42:24.395: E/AndroidRuntime(25381):    at dalvik.system.NativeStart.main(Native Method)
03-19 15:42:25.685: I/Process(25381): Sending signal. PID: 25381 SIG: 9

Anybody have an idea how to solve these stack trace error.

Stephen
  • 9,899
  • 16
  • 90
  • 137
anuj
  • 429
  • 3
  • 7
  • 14
  • You have to get the a,b values in the onclick method..before it will be "" only.. – kalyan pvs Mar 19 '14 at 10:21
  • 3
    change the if (a=="" && b=="") to if (a.length()==0 || b.length()==0) The alert should be rised event a is empty or b is emmpty – VinhNT Mar 19 '14 at 10:22
  • @VinhNT that check should not be done.. wat if that edittext filled with a space or other chars? same number format exception will occour.. This check is ok if user leaves the edittext empty. – Antony Mar 19 '14 at 10:29
  • possible duplicate of [How do I compare strings in Java?](http://stackoverflow.com/questions/513832/how-do-i-compare-strings-in-java) – donfuxx Mar 19 '14 at 10:33
  • 1
    @Antony, well, i see your oponion, so, the best way for this case is try and catch the parse method, if any exception raised, notify the user about her/his wrong data, otherwise, simply accept the number – VinhNT Mar 19 '14 at 10:37
  • @VinhNT exactly... thats the perfect solution – Antony Mar 19 '14 at 10:40

10 Answers10

8

Use following.

 a = e1.getText().toString().trim();    
 b = e2.getText().toString().trim(); 
 if (a.equals("") && b.equals("") ){

 }
3

If we use .equals(), still chance of NumberFormatException, because if user enters a space or special chars exception will arise. Changing your code like this..

@Override
public void onClick(View arg0) {
try{
        a = e1.getText().toString();
        b = e2.getText().toString();
        int result = Integer.parseInt(a) + Integer.parseInt(b);
        t1.setText(Integer.toString(result));
        InputMethodManager imm = (InputMethodManager)getSystemService(
                  Context.INPUT_METHOD_SERVICE);
        imm.hideSoftInputFromWindow(add.getWindowToken(), 0);
    }
 catch(NumberFormatException e)
   {
     AlertDialog.Builder a1 = new AlertDialog.Builder(c);


            // Setting Dialog Title
            a1.setTitle("Alert Dialog");

            // Setting Dialog Message
            a1.setMessage("Filed is Empty or Invalid Number");

            a1.setPositiveButton("yes",
                    new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog,
                                int button1) {
                            // if this button is clicked, close
                            // current activity
                            dialog.cancel();
                        }

                    });

            // Showing Alert Message
            AlertDialog alertDialog = a1.create();
            a1.show();
  }
  }

  });
Aditya Vyas-Lakhan
  • 13,409
  • 16
  • 61
  • 96
Antony
  • 603
  • 6
  • 14
1
if (a=="" && b=="")

Do not use == for string comparison. See How do I compare strings in Java?

NumberFormatException

Since you're parsing user-provided input, you should catch the exception and handle the parse error accordingly.

Community
  • 1
  • 1
laalto
  • 150,114
  • 66
  • 286
  • 303
0

First of all you shouldnt compare string values using == operator, Instead you should use equals() method from String class.

Next Change.

public void onClick(View arg0) 
{
    // First fetch the values of a & b here instead of onCreate() method
      a = e1.getText().toString().trim();    // trim() method will remove any white spaces
      b = e2.getText().toString().trim(); 
     if (a.equals("") && b.equals("") )
     {
    ....

Change the above things, and your code should work, perfectly.

Lucifer
  • 29,392
  • 25
  • 90
  • 143
0

You are converting your edittext's value's to string like below in your code

a = e1.getText().toString();
b = e2.getText().toString();

So you have to use

a.equals("") && b.equals("")

instead of

a=="" && b==""

and one more thing you have to change is, this line

AlertDialog.Builder a1 = new AlertDialog.Builder(c);

with

AlertDialog.Builder a1 = new AlertDialog.Builder(Calci.this);
InnocentKiller
  • 5,234
  • 7
  • 36
  • 84
  • still chance of NumberFormatException, because if user enters a space or special chars exception will arise. – Antony Mar 19 '14 at 10:57
0

For the part:

 int result = Integer.parseInt(a) + Integer.parseInt(b);
        t1.setText(Integer.toString(result));

try this:

int result = Integer.valueOf(a) + Integer.valueOf(b);
        t1.setText(Integer.toString(result));

That helped me some time ago on a very similar problem

Fraggles
  • 463
  • 4
  • 20
0

please make change as below,

    add.setOnClickListener(new View.OnClickListener() {

@Override
public void onClick(View arg0) {
     if (a.equals("") && b.equals("") )
 {
            AlertDialog.Builder a1 = new AlertDialog.Builder(c);


            // Setting Dialog Title
            a1.setTitle("Alert Dialog");

            // Setting Dialog Message
            a1.setMessage("PLEASE ENTER SOMETHING");

            a1.setPositiveButton("yes",
                    new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog,
                                int button1) {
                            // if this button is clicked, close
                            // current activity
                            dialog.cancel();
                        }

                    });

            // Showing Alert Message
            AlertDialog alertDialog = a1.create();
            a1.show();

        }

    else{
        int result = Integer.parseInt(a) + Integer.parseInt(b);
        t1.setText(""+result);
        InputMethodManager imm = (InputMethodManager)getSystemService(
                  Context.INPUT_METHOD_SERVICE);
            imm.hideSoftInputFromWindow(add.getWindowToken(), 0);
    }

}

});

0

The issue is misleading, it is about the size of integer, since java int is: 2^32-1, your integer can be 10 digits log, eg: 0123456789. However if the integer is 11 digits, eg: 0123456789***1***. then you need to use BigInteger, see: https://developer.android.com/reference/java/math/BigInteger.html

Shoresh
  • 129
  • 1
  • 4
0

This might be a bit late but am sure it will help someone in the future.

You have to nest Strings a and b in the onclick.I did that on mine and worked seamlessly.

recussive
  • 11
  • 2
0

If you are using EditText and expect an integer value from user then the best way is to use inputType attribute in your EditText xml file.

android:inputType="numberDecimal"