views:

514

answers:

1

I don't understand why I'm getting this error. I'm using AsyncTask to run some processes in the background.

I have:

protected void onPreExecute() 
{
    connectionProgressDialog = new ProgressDialog(SetPreference.this);
    connectionProgressDialog.setCancelable(true);
    connectionProgressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
    connectionProgressDialog.setMessage("Connecting to site...");
    connectionProgressDialog.show();

    downloadSpinnerProgressDialog = new ProgressDialog(SetPreference.this);
    downloadSpinnerProgressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
    downloadSpinnerProgressDialog.setMessage("Downloading wallpaper...");
}

When I get into doInBackground() depending on a condition I:

[...]    
connectionProgressDialog.dismiss();
downloadSpinnerProgressDialog.show();
[...]

Whenever I try downloadSpinnerProgressDialog.show() I receive the error.

Any ideas guys?

+2  A: 

show() must be called from UI thread, while doInBackground() runs on different thread (that's main reason why AsyncTask was designed). You have to call show() either in onPogressUpdate() or at onPostExecute(). For example:

class ExampleTask extends AsyncTask<String, String, String>{

//Your onPreExecute method....

@Override
protected String doInBackground(String... params) {
     //...your code 
     if(condition_is_true){
        this.publishProgress("Show the dialog");
     } 
    }
    return "Result";
}

@Override
protected void onProgressUpdate(String... values) {
    super.onProgressUpdate(values);
    connectionProgressDialog.dismiss();
    downloadSpinnerProgressDialog.show();
}
}
Konstantin Burov
Awesome man... thanks Kon :P Feel like a noob trying to code for the Android for the very first time.
mlevit