0

I would like to make it so that when the editText fields are empty, no result is shown instead of the app crashing.

I read over this result here: How to break out or exit a method in Java?

as well as some other results based on whether the number was negative or positive. I've been working in this for about an hour and I'm throwing in the towel. I'm new to this, and I think I must just not be putting the if statement in the correct location?

Here's the code. Any pointers in the right direction would be helpful. Thanks.

public class incomePage extends AppCompatActivity {
    EditText perYearAmount;
    EditText perMonthAmount;
    EditText perWeekAmount;
    Button totalButton;
    TextView addResult;


    double year, month, week, sum;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_income_page);
        perYearAmount = (EditText) findViewById(R.id.perYearAmount);
        perMonthAmount = (EditText) findViewById(R.id.perMonthAmount);
        perWeekAmount = (EditText) findViewById(R.id.perWeekAmount);
        totalButton = (Button) findViewById(R.id.totalButton);
        addResult = (TextView) findViewById(R.id.totalMonthlyIncome);


        totalButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                year = Double.parseDouble(perYearAmount.getText().toString());
                month = Double.parseDouble(perMonthAmount.getText().toString());
                week = Double.parseDouble(perWeekAmount.getText().toString());
                sum = year + month + week;
                addResult.setText(Double.toString(sum));
                if (perYearAmount.getText().toString().equals("")) {
                    return;
                }
                if (perMonthAmount.getText().toString().equals("")) {
                    return;
                }
                if (perWeekAmount.getText().toString().equals("")) {
                    return;
                }
                if (totalButton.getText().toString().equals("")) {
                    return;
                }
                if (addResult.getText().toString().equals("")) {
                    return;
                }

            }
        });

    }
}

Here's the logCat error. You guys are fast!!

08-24 15:49:31.799 15154-16038/com.example.android.budgeit10 D/OpenGLRenderer: Enabling debug mode 0
08-24 15:49:35.123 15154-16038/com.example.android.budgeit10 D/OpenGLRenderer: endAllStagingAnimators on 0xb8937048 (RippleDrawable) with handle 0xb897a910
08-24 15:49:36.645 15154-16038/com.example.android.budgeit10 D/OpenGLRenderer: endAllStagingAnimators on 0xb89e95a0 (RippleDrawable) with handle 0xb89ebac8
08-24 15:49:50.694 15154-15154/com.example.android.budgeit10 D/AndroidRuntime: Shutting down VM
08-24 15:49:50.695 15154-15154/com.example.android.budgeit10 E/AndroidRuntime: FATAL EXCEPTION: main
                                                                               Process: com.example.android.budgeit10, PID: 15154
                                                                               java.lang.NumberFormatException: Invalid double: ""
                                                                                   at java.lang.StringToReal.invalidReal(StringToReal.java:63)
                                                                                   at java.lang.StringToReal.parseDouble(StringToReal.java:267)
                                                                                   at java.lang.Double.parseDouble(Double.java:301)
                                                                                   at com.example.android.budgeit10.incomePage$1.onClick(incomePage.java:34)
                                                                                   at android.view.View.performClick(View.java:4785)
                                                                                   at android.view.View$PerformClick.run(View.java:19884)
                                                                                   at android.os.Handler.handleCallback(Handler.java:739)
                                                                                   at android.os.Handler.dispatchMessage(Handler.java:95)
                                                                                   at android.os.Looper.loop(Looper.java:135)
                                                                                   at android.app.ActivityThread.main(ActivityThread.java:5343)
                                                                                   at java.lang.reflect.Method.invoke(Native Method)
                                                                                   at java.lang.reflect.Method.invoke(Method.java:372)
                                                                                   at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:905)
                                                                                   at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:700)
Community
  • 1
  • 1
David Shinabarger
  • 143
  • 1
  • 3
  • 12
  • I think you are solving the real problem in an incorrect way. Why does your app crash? What is the error? – Code-Apprentice Aug 24 '16 at 19:39
  • post the logcat / error message – ΦXocę 웃 Пepeúpa ツ Aug 24 '16 at 19:40
  • Please add the crash log to your question (at a guess I'd say a likely cause is a `NumberFormatException`, if you're getting a crash) – PPartisan Aug 24 '16 at 19:41
  • @Code-Apprentice I'll edit the post with it. Thanks. – David Shinabarger Aug 24 '16 at 19:50
  • "StringToReal.java:63" means that the error occurs on line 63 in `StringToReal.java`. What line is this? – Code-Apprentice Aug 24 '16 at 19:54
  • @Code-Apprentice I don't think I have a StringToReal.java, at least not that I can find in the app->java folders. – David Shinabarger Aug 24 '16 at 20:13
  • My bad. In general, you should look down the list of methods in the stacktrace and find the one closest to the top which is one you wrote. Looking more closely, `StringToReal` is from the `java.lang` package, so definitely not your code. In this case, look at `at com.example.android.budgeit10.incomePage$1.onClick(incomePage.java:34)` This is line 34 in `incomePage.java`. The error occurs in an `onClick()` method of an anonymous inner class. – Code-Apprentice Aug 26 '16 at 21:29

3 Answers3

2

You need to check if the EditText has text in it before trying to parse the (possibly) non-existing text as a numeric value. For example

String yearString = perYearAmount.getText().toString();

if (!"".equals(yearString)) {
    year = Double.parseDouble(yearString);
}

Note that I create a temporary variable yearString in order to avoid typing and executing perYearAmount.getText().toString() twice.

Code-Apprentice
  • 81,660
  • 23
  • 145
  • 268
0

Use TextUtils.

totalButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {

        if (TextUtils.isEmpty(perYearAmount.getText().toString())||
            TextUtils.isEmpty(perMonthAmount.getText().toString())||
            TextUtils.isEmpty(perWeekAmount.getText().toString()))   {

                addResult.setText(""); // if any of the fields is empty, add nothing to textview

        } else {
            year = Double.parseDouble(perYearAmount.getText().toString());
            month = Double.parseDouble(perMonthAmount.getText().toString());
            week = Double.parseDouble(perWeekAmount.getText().toString());
            sum = year + month + week;
            addResult.setText(Double.toString(sum));
        }
        }
    });
Sudip Podder
  • 830
  • 11
  • 25
  • That seemed to do the trick. I don't really understand the "why" behind it at this point, but I'll get there slowly but surely. Thanks!! – David Shinabarger Aug 24 '16 at 20:15
0

The crash is caused by a NumberFormatException, which is thrown by the Double.parseDouble() method when the argument is not a parsable double. In your error log, this appears as an empty String:

java.lang.NumberFormatException: Invalid double: ""

To get around this, you could surround any Double.parseDouble() calls in a try/catch block:

try {
    Double.parseDouble(anEditText.getText().toString());
} catch (NumberFormatException nfe) {
    //anEditText does not contain a parsable Double
}

Edit: To create an example using your code:

double year = 0;
double month = 0;
try {
    year = Double.parseDouble(perYearAmount.getText().toString());
    month = Double.parseDouble(perMonthAmount.getText().toString());
} catch (NumberFormatException nfe) {
    Toast.makeText(this, "Please enter a valid number and try again", Toast.LENGTH_SHORT).show();
    return;
}

double sum = year + month;
//etc...
PPartisan
  • 8,173
  • 4
  • 29
  • 48