Android java.lang.NumberFormatException: Invalid int: "" 异常

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/22502658/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-20 06:05:11  来源:igfitidea点击:

java.lang.NumberFormatException: Invalid int: "" EXCEPTION

androidexception

提问by anuj

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

如果用户将 edittext 留空,则会发生错误 java.lang.NumberFormatException: Invalid int: ""。错误来自行

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

and also at line

并且在线

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

Calci.java

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.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.

任何人都知道如何解决这些堆栈跟踪错误。

回答by user3007252

Use following.

使用以下。

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

 }

回答by Antony

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..

如果我们使用.equals(),仍然有机会NumberFormatException,因为如果用户输入空格或特殊字符会出现异常。像这样改变你的代码..

@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();
  }
  }

  });

回答by laalto

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

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

不要==用于字符串比较。请参阅如何比较 Java 中的字符串?

NumberFormatException

数字格式异常

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

由于您正在解析用户提供的输入,因此您应该捕获异常并相应地处理解析错误。

回答by Lucifer

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

首先,您不应该使用==运算符比较字符串值,而应该使用equals()String 类中的方法。

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.

更改上述内容,您的代码应该可以完美运行。

回答by InnocentKiller

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);

回答by Fraggles

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

前段时间在一个非常相似的问题上帮助了我

回答by Sekhar Madhiyazhagan

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);
    }

}

});

});

回答by Shoresh

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

这个问题是误导,它是关于整数的大小,因为java int是:2^32-1,你的整数可以是10位log,例如:0123456789。但是如果整数是11位,例如:0123456789*** 1***。那么你需要使用BigInteger,见:https: //developer.android.com/reference/java/math/BigInteger.html

回答by recussive

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.

您必须将字符串 a 和 b 嵌套在 onclick.I 中,并且无缝地工作。

回答by Sachidananda Sahu

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.

如果您使用 EditText 并期望来自用户的整数值,那么最好的方法是在 EditText xml 文件中使用 inputType 属性。

android:inputType="numberDecimal"