简体   繁体   中英

Integer from EditText Problems

I want to add 2 numbers and show the result on the screen. Thats why i have 2 EditText (Number1 & Number2) , a Button (PLUS) and a TextView that shows the result.

Problem is that probably something goes wrong with integers and EditText.
Logcat says : "Caused by: java.lang.NumberFormatException: Invalid int: "

This is the code :

public class MainActivity extends Activity {

EditText FirstNum;
EditText SecondNum;
Button PlusButton;
TextView Result;
int Number1;
int Number2;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    FirstNum = (EditText) findViewById(R.id.FirstNum);
    SecondNum = (EditText) findViewById(R.id.SecondNum);


        Number1 = Integer.parseInt(FirstNum.getText().toString());
        Number2 = Integer.parseInt(SecondNum.getText().toString());



    PlusButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
        Result.setText(plusmethod(Number1,Number2)+"");
        }
    });

}


int plusmethod(int a, int b) {
    return a + b;
}

UPDATE : Here is my full Logcat :

 Process: com.gss.dejix.calq, PID: 20008
    java.lang.RuntimeException: Unable to start activity ComponentInfo{com.gss.dejix.calq/com.gss.dejix.calq.MainActivity}: java.lang.NullPointerException
            at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2412)
            at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2470)
            at android.app.ActivityThread.access$900(ActivityThread.java:174)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1307)
            at android.os.Handler.dispatchMessage(Handler.java:102)
            at android.os.Looper.loop(Looper.java:146)
            at android.app.ActivityThread.main(ActivityThread.java:5593)
            at java.lang.reflect.Method.invokeNative(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:515)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1283)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1099)
            at dalvik.system.NativeStart.main(Native Method)
     Caused by: java.lang.NullPointerException
            at com.gss.dejix.calq.MainActivity.onCreate(MainActivity.java:36)
            at android.app.Activity.performCreate(Activity.java:5458)
            at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1093)
            at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2376)
            at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2470)
            at android.app.ActivityThread.access$900(ActivityThread.java:174)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1307)
            at android.os.Handler.dispatchMessage(Handler.java:102)
            at android.os.Looper.loop(Looper.java:146)
            at android.app.ActivityThread.main(ActivityThread.java:5593)
            at java.lang.reflect.Method.invokeNative(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:515)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1283)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1099)
            at dalvik.system.NativeStart.main(Native Method)

Move code

    Number1 = Integer.parseInt(FirstNum.getText().toString());
    Number2 = Integer.parseInt(SecondNum.getText().toString());

under your PlusButton.setOnClickListener(....)

Like

  PlusButton.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {

    if(!TextUtils.isEmpty(FirstNum.getText().toString()) && !TextUtils.isEmpty(SecondNum.getText().toString())){

     Number1 = Integer.parseInt(FirstNum.getText().toString());
     Number2 = Integer.parseInt(SecondNum.getText().toString());
     Result.setText(""+plusmethod(Number1,Number2)+"");

    }

    }
});

and also you need to initialize your TextView Result;

Check editext value before parse to int otherwise it gives NumberFormatException :

if(FirstNum.getText().toString().trim().length()>0){
     Number1 = Integer.parseInt(FirstNum.getText().toString());
}
if(SecondNum.getText().toString().trim().length()>0){
     Number2 = Integer.parseInt(SecondNum.getText().toString());
}

You also missing to initialize Result and PlusButton first initialize it before use.

Example :

protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        FirstNum = (EditText) findViewById(R.id.FirstNum);
        SecondNum = (EditText) findViewById(R.id.SecondNum);
        Result = (TextView) findViewById(R.id.Result);
        PlusButton = (Button) findViewById(R.id.PlusButton);

        PlusButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                boolean isValid=true;
                if(FirstNum.getText().toString().trim().length()<=0){
                    FirstNum.setError("Value Required");
                    isValid=false;
                }
                if(SecondNum.getText().toString().trim().length()<=0){
                    SecondNum.setError("Value Required");
                    isValid=false;
                }
                if(isValid){
                    Result.setText(String.valueOf(plusmethod(Integer.parseInt(FirstNum.getText().toString()),Integer.parseInt(SecondNum.getText().toString()))));
                }

            }
        });
    }

you are not initialize the textview Result

   Result =  (TextView ) findViewById(R.id.result);
   PlusButton=(Button)findViewById(R.id.plusbutton);

also do this

PlusButton.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
     Number1 = Integer.parseInt(FirstNum.getText().toString());
     Number2 = Integer.parseInt(SecondNum.getText().toString());
    Result.setText(""+plusmethod(Number1,Number2)+"");
    }
});

you have to write your code inside try...catch block like this,

PlusButton.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
try{
    Result.setText(plusmethod(Number1,Number2)+"");
}catch(NumberFormatException e){
}
});

It is very clear that you are going to use get only numeric value from Edittext. So you can make the edit text as android:inputType="number"

<EditText
android:id="@+id/edtPhoneNo"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:inputType="number"/>

if you are using : Number1 = Integer.parseInt(FirstNum.getText().toString()); alphabetic value will aslo used. So that's the reason you are getting that exception. If you not getting solution, add it on comments.

First Check for null or empty: after that parse it in integer:

public static boolean isNullOrEmpty(final String pStr) {
    return pStr == null || pStr.trim().length() == 0 || pStr.trim().equalsIgnoreCase("null");
}

& one more thing in edit text make validation

 android:digits="0123456789"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM