0

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

Omar Einea
  • 2,478
  • 7
  • 23
  • 35
Otto
  • 19
  • 8

3 Answers3

0

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

Benkerroum Mohamed
  • 1,867
  • 3
  • 13
  • 19
0

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.

Dennis Soemers
  • 8,090
  • 2
  • 32
  • 55
Madhan
  • 555
  • 5
  • 23
  • Ok, so how do i check for text emptiness? – Otto Mar 22 '18 at 17:57
  • You can use the handy method TextUtils.isEmpty(caloriesIn.getText().toString()). If it returns false, you can use parseInt. Also use digits as the inputType for the edit text so that user can enter digits only in your edit text. – Madhan Mar 22 '18 at 18:00
  • TextUtils.isEmpty(caloriesIn.getText().toString()) – Otto Mar 22 '18 at 18:07
  • But how do i take that and make it into an if statement? – Otto Mar 22 '18 at 18:07
0
 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 :)

Chirag
  • 555
  • 1
  • 5
  • 20