TAGS :Viewed: 1 - Published at: a few seconds ago

[ Android: Progress Dialog error in AysncTask ]

I have some code that does some processing in an AsyncTask, while this is running I would like to display a Progress Dialog. At various points I was hoping to update the message but I'm having some trouble. Heres what I have so far:

class ShowDialogAsyncTask extends AsyncTask<Void, String, Void>{

    private ProgressDialog progressSpinner;

        protected void onPreExecute() {
        ProgressDialog progressSpinner = new ProgressDialog(MainActivity.this);
        progressSpinner.setTitle("File Download");
        progressSpinner.setMessage("Connecting to Internet");

        protected Void doInBackground(Void... params) 
            try {
                onProgressUpdate("Downloading File");
                //do some stuff
            } catch (IOException e) {
                result = "Error";

            return null;

        protected void onProgressUpdate(String... values) 
        }catch(Exception e){Log.e("onProgressUpdate","Error!");}

        protected void onPostExecute(Void result) 

The code which I was hoping would have updated the message doesn't work, it just throws an exception. Then the whole thing crashes when I attempt to dismiss the the progress dialog.

I am pretty new to android development so I would very much appreciate any pointers.

The Logcat entries where it all goes a bit pear shaped.

03-22 22:59:30.189: W/dalvikvm(8133): threadid=3: thread exiting with uncaught exception (group=0x4001b188)
03-22 22:59:30.189: E/AndroidRuntime(8133): Uncaught handler: thread main exiting due to uncaught exception
03-22 22:59:30.195: E/AndroidRuntime(8133): java.lang.NullPointerException


It appears that my issue was where I had been declaring the progress dialog box. I eventually figured out that I could declare the progress dialog in a newly created constructor like so

progressSpinner = new ProgressDialog(mContext);

It would then allow all the other methods of the AsyncTask class access to update the message.

Answer 1

the problem is probably how you refer to your MainActivity while creating the ProgressDialog. Add a public constructor to your AsyncTask and a class field named mContext:

        public ShowDialogAsyncTask(Context c){
           mContext = c;

Pass this in your MainActivity while creating an object of your class:

         ShowDialogAsyncTask task = new ShowDialogAsyncTask(this);

in your AsyncTask, create the ProgressDialog using that context