每当我的 EditText 为空并按下按钮时,我的应用程序就会崩溃

My app crashes whenever my EditText is empty and I press a button

问题是,每次我点击我的应用程序中的按钮时,每当我的 EditText 之一或两者都为空时,应用程序就会崩溃。

我的想法是,我将在名为 caloriesIn 的 EditText 中写入卡路里,它会在文本字段 caloriesOut 中输出一个 int。 同样的想法也适用于 "fat".

问题只是总结一下,如果我在卡路里中写了一些东西,但不在脂肪中写任何东西,或者只是不在其中任何一个中写任何东西,应用程序就会崩溃。

我的代码:

public class MainActivity extends AppCompatActivity {

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


        Button button = (Button) findViewById(R.id.button);
        button.setOnClickListener( new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                EditText caloriesIn = (EditText) findViewById(R.id.caloriesIn);
                EditText fatIn = (EditText) findViewById(R.id.fatIn);
                TextView caloriesOut = (TextView) findViewById(R.id.caloriesOut);
                TextView fatOut = (TextView) findViewById(R.id.fatOut);

                int calories = Integer.parseInt(caloriesIn.getText().toString());
                int fat = Integer.parseInt(fatIn.getText().toString());
                int caloriesResult = calories;
                int fatResult = fat;

                caloriesOut.setText(caloriesResult + "");
                fatOut.setText(fatResult + "");


            }
        });

    }
}

崩溃报告:

03-22 17:20:02.512 22193-22193/ottolopez.healthynote I/Choreographer: Skipped 47 frames! The application may be doing too much work on its main thread. 03-22 17:20:02.556 22193-22193/ottolopez.healthynote V/View: dispatchProvideAutofillStructure(): not laid out, ignoring 0 children of 1073741833 03-22 17:20:02.561 22193-22193/ottolopez.healthynote I/AssistStructure: Flattened final assist data: 2936 bytes, containing 1 windows, 11 views 03-22 17:20:05.047 22193-22193/ottolopez.healthynote D/AndroidRuntime: Shutting down VM 03-22 17:20:05.049 22193-22193/ottolopez.healthynote E/AndroidRuntime: FATAL EXCEPTION: main Process: ottolopez.healthynote, PID: 22193 java.lang.NumberFormatException: For input string: "" at java.lang.Integer.parseInt(Integer.java:620) at java.lang.Integer.parseInt(Integer.java:643) at ottolopez.healthynote.MainActivity.onClick(MainActivity.java:28) at android.view.View.performClick(View.java:6294) at android.view.View$PerformClick.run(View.java:24770) at android.os.Handler.handleCallback(Handler.java:790) at android.os.Handler.dispatchMessage(Handler.java:99) at android.os.Looper.loop(Looper.java:164) at android.app.ActivityThread.main(ActivityThread.java:6494) at java.lang.reflect.Method.invoke(Native Method) at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:807)

在您的 activity 上定义此方法:

public boolean isParsable(String input){
    boolean parsable = true;
    try{
        Integer.parseInt(input);
    }catch(NumberFormatException e){
        parsable = false;
    }
    return parsable;
}

然后像这样更新您的代码:

     public class MainActivity extends AppCompatActivity {

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


        Button button = (Button) findViewById(R.id.button);
        button.setOnClickListener( new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                EditText caloriesIn = (EditText) findViewById(R.id.caloriesIn);
                EditText fatIn = (EditText) findViewById(R.id.fatIn);
                TextView caloriesOut = (TextView) findViewById(R.id.caloriesOut);
                TextView fatOut = (TextView) findViewById(R.id.fatOut);
                String caloriesString = caloriesIn.getText().toString();
                int calories = 0;
                if (isParsable(caloriesString)){
                    calories = Integer.parseInt(caloriesString);
                    int caloriesResult = calories;
                    caloriesOut.setText(caloriesResult + "");
                }

                String fatString = caloriesIn.getText().toString();
                int fat = 0;
                if (isParsable(fatString)){
                    fat = Integer.parseInt(fatString);
                    int fatResult = fat;
                    fatOut.setText(fatResult + "");
                }

            }
        });

    }


    public static boolean isParsable(String input){
        boolean parsable = true;
        try{
            Integer.parseInt(input);
        }catch(NumberFormatException e){
            parsable = false;
        }
        return parsable;
    }

}

希望对您有所帮助

问题是 Integer.parseInt() 不处理不是数字的空字符串。因此,您需要检查文本是否为空,然后使用 Integer.parseInt()。您也可以在使用 parseInt 之前使用 isDigitsOnly 方法。

 int calories = Integer.parseInt(caloriesIn.getText().toString());
 int fat = Integer.parseInt(fatIn.getText().toString());

主要问题出在这些行中,如果您在此处传递任何字符或将其留空,则会出错,要解决这些问题,请将这些行添加到您的代码中

String calIn =  caloriesIn.getText().toString(); //first take input in String for checking
    String fatInStr = fatIn.getText().toString(); //first take input in String for checking

    if (calIn.isEmpty()) {
         Toast.makeText(...);//inform user that calories input field is empty
        return;
    } else if (fatInStr.isEmpty()) {
         Toast.makeText(...);//inform user that fat input field is empty
        return;
    } else if (!calIn.matches("[0-9]+")) {
         Toast.makeText(...);//inform user that calories input field contains invalid data
        return;
    } else if (!fatInStr.matches("[0-9]+")) {
        // Toast.makeText(...);//inform user that fat input field contains invalid data
        return;
    }
    int calories = Integer.parseInt(calIn.trim()); // trim method removes any leading and trailing spaces
    int fat = Integer.parseInt(fatInStr.trim());

现在,当文本为空且不是数字时,应用程序是安全的:)