Northumber
Northumber

Reputation: 315

New AsyncTask correction, app crash

Please, can anyone correct this code? I'm getting crazy. The app crashes, but the code seems good. I want to display a progress dialog during pi calculation. Is the reference of strings or the order of params? (Or the incorrect calculation of pi?).

new AsyncTask<Void, Void, String>() {
    ProgressDialog dialog;

    @Override
    public void onPreExecute() {
        dialog.setMessage("Calculating...");
        dialog.show();
    }

    @Override
    public String doInBackground(Void... params) {

        double max_num = 100000000;
        double min_num = 1;
        double a = 0;

        long startTime = System.currentTimeMillis();
        while (min_num < max_num) {
            a += 4 / min_num;
            min_num += 2;
            a -= 4 / min_num;
            min_num += 2;
        }
        long endTime = System.currentTimeMillis();

        long total_time = endTime - startTime;

        String time = Long.toString(total_time);

        return time;

    }

    @Override
    public void onPostExecute(String time) {

        if (dialog.isShowing()) {
            dialog.dismiss();

            String ms = "ms";
            TextView time_txt = (TextView) findViewById(R.id.time_txt);
            TextView finished = (TextView) findViewById(R.id.finished);
            TextView time_ms = (TextView) findViewById(R.id.time_ms);
            finished.setText("Finished!");
            time_txt.setText("TOTAL TIME");
            time_ms.setText(time + ms);
        }
    }

}.execute();

Upvotes: 0

Views: 80

Answers (1)

Pankaj
Pankaj

Reputation: 8058

Initialise your dialog and your problem will be solved like this:

 @Override
 public void onPreExecute() {
        dialog = new Dialog(YourActivity.this); //add this line
        dialog.setMessage("Calculating...");
        dialog.show();
 }

Upvotes: 1

Related Questions