user650309
user650309

Reputation: 2899

Android application crashing despite exception caught

I'm writing a simple app which allows a user to enter their income and it deducts tax, then saves the amount in a file for future reference. Whenever I try to enter an amount I get a warning saying the application has stopped unexpectedly. Here is my code:

public void onClick(View v) {
    // TODO Auto-generated method stub
    try {

        if (preTax !=null){         
            Double incomeAmount = Double.parseDouble(preTax.getText().toString());
            incomeAmount =- (20 *100)/incomeAmount;     
            Double incomeRounded = Round(incomeAmount);
            Toast.makeText(null, "Your income minus tax = "+incomeRounded, Toast.LENGTH_LONG).show();


            FileOutputStream fos = openFileOutput("income", Context.MODE_PRIVATE);
            fos.write("1000".getBytes());
            fos.close();
        }
        else {

            Double incomeAmount = Double.parseDouble(postTax.getText().toString());
            Double incomeRounded = Round(incomeAmount);
            Toast.makeText(null, "Your income is: "+ incomeRounded, Toast.LENGTH_LONG).show();


            FileOutputStream fos = openFileOutput("income", Context.MODE_PRIVATE);
            fos.write("1000".getBytes());
            fos.close();
        }

    } catch (Exception e){
        Toast.makeText(null, "Please fill in the catagories" + e, Toast.LENGTH_LONG).show();
    }
}

This issue was happening before the fileoutstream stuff was added, so I know that that isn't the issue, but it is not clear to me what is. Program crashes regardless of whether the EditText is empty or not. Surely the try/catch should catch any errors?

Upvotes: 0

Views: 194

Answers (2)

james
james

Reputation: 26271

Toast.makeText(null, "Please fill in the catagories" + e, Toast.LENGTH_LONG).show();

should be

Toast.makeText(v.getContext(), "Please fill in the catagories" + e, Toast.LENGTH_LONG).show();

you can't pass null in for the context, it needs to be valid.

Upvotes: 3

Philip Sheard
Philip Sheard

Reputation: 5815

Passing in null for the context does not exactly help. Your app in blowing up, getting caught and then blowing up again.

Upvotes: 2

Related Questions