简体   繁体   English

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

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

The problem is that each time I click on the button in my app, then whenever one of my EditText or both are empty, the app will crash. 问题是,每当我单击应用程序中的按钮时,只要我的一个或两个EditText为空,该应用程序就会崩溃。

The idea is that I will write the calories in the EditText called caloriesIn and it will put out an int in the caloriesOut which is a textfield. 这个想法是,我会写在卡路里EditText称为caloriesIn,它将推出一个intcaloriesOut这是一个文本框。 The same idea goes for "fat". “脂肪”也有同样的想法。

The problem just to sum up is that if I write something in the calories, but don't write anything in fat, or just don't write anything in either of them, the app will crash. 综上所述,问题是,如果我用卡路里写一些东西,但是不写任何脂肪,或者只是不写任何东西,那么应用程序将崩溃。

My Code: 我的代码:

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


            }
        });

    }
}

Crash report: 崩溃报告:

03-22 17:20:02.512 22193-22193/ottolopez.healthynote I/Choreographer: Skipped 47 frames! 03月22日17:20:02.512 22193-22193 / ottolopez.healthynote I /编舞:跳过了47帧! 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$1.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 androi 03月22日17:20:02.556 22193-22193 / ottolopez.healthynote V /视图:dispatchProvideAutofillStructure():未布局,忽略了10个孩子的1073741833 03-22 17:20:02.561 22193-22193 / ottolopez.healthynote I / AssistStructure :扁平化的最终辅助数据:2936字节,包含1个窗口,11个视图03-22 17:20:05.047 22193-22193 / ottolopez.healthynote D / AndroidRuntime:关闭VM 03-22 17:20:05.049 22193-22193 / ottolopez .healthynote E / AndroidRuntime:致命例外:主进程:ottolopez.healthynote,PID:22193 java.lang.NumberFormatException:对于输入字符串:java.lang.Integer.parseInt(Integer.java:620)处的“” .Integer.parseInt(Integer.java:643)位于ottolopez.healthynote.MainActivity $ 1.onClick(MainActivity.java:28)在android.view.View.performClick(View.java:6294)在android.view.View $ PerformClick .run(View.java:24770)在android.os.Handler.handleCallback(Handler.java:790)在android.os.Handler.dispatchMessage(Handler.java:99)在android.os.Looper.loop(Looper。 java:164)在androi d.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) d.app.ActivityThread.main(ActivityThread.java:6494)位于com.android.internal.os.RuntimeInit $ MethodAndArgsCaller.run(RuntimeInit.java:438)处的java.lang.reflect.Method.invoke(本机方法) com.android.internal.os.ZygoteInit.main(ZygoteInit.java:807)

Define this methode on your activity : 在您的活动中定义此方法:

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

Then updated your code like this : 然后像这样更新您的代码:

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

}

Hope this helps 希望这可以帮助

The thing is Integer.parseInt() doesn't handle empty string which is not a number. 问题是Integer.parseInt()不能处理不是数字的空字符串。 So, you need to check for text emptiness and then use Integer.parseInt() . 因此,您需要检查文本是否为空,然后使用Integer.parseInt() Also you can use isDigitsOnly method before using parseInt. 您也可以在使用parseInt之前使用isDigitsOnly方法。

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

The main problem is in these lines, it will give error is you pass any character here or leave it blank, to solve these add these lines to your code 主要问题是在这些行中,如果您在此处传递任何字符或将其保留为空白,则会产生错误,以解决这些问题,并将这些行添加到代码中

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

Now app is safe when text is empty and is not a digit :) 现在,当文本为空且不是数字时,应用是安全的:)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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