1''
1''

Reputation: 27095

Asynctask with Progressdialog

I'm using an Asynctask to execute a time-consuming method, doStuff(), which among other things allocates global data structures. A debugger confirms that doStuff() is called, but when a new view is drawn at the end of the Asynctask, I get a null pointer exception while accessing the global data structures. Here is the code:

public class MyTask extends AsyncTask<Void, Void, Void> {
    protected ProgressDialog dialog;

    public MyTask (Context context) {
        dialog = new ProgressDialog(context);
    }

    @Override
    protected void onPreExecute() { 
       super.onPreExecute();
       dialog.setMessage("Foo");
       dialog.show();    
    }

    @Override
    protected Void doInBackground(Void... params) {
        doStuff();
        return null;
    }

    @Override
    protected void onPostExecute(Void result) {
        super.onPostExecute(result);
        dialog.dismiss();
    }
}

I execute the Asynctask from multiple activities using new MyTask(this).execute();.

Upvotes: 0

Views: 213

Answers (2)

iagreen
iagreen

Reputation: 31996

AsyncTask is a really a convenience wrapper around a background thread and a handler. You are executing code before the background task finishes. To know when the background task is finished, you need to put the code you want to execute or otherwise signal your main activity in onPostExecute (which will run on the UI/main thread) that the task is complete. For more details, see the using AsyncTask section of the Processes and Threads guide.

Upvotes: 2

Jose Manuel
Jose Manuel

Reputation: 807

You must declare the ProgressDialog in the Activity that you are using your AsyncTask

Upvotes: 0

Related Questions