简体   繁体   中英

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.

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

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. So, you need to check for text emptiness and then use Integer.parseInt() . Also you can use isDigitsOnly method before using parseInt.

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

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