daemon54
daemon54

Reputation: 1105

ProgressDialog.show inside AsyncTask stop my Program from execution

Here's the prototype of my code:-

class something extends Activity
{
    protected void onCreate(Bundle savedInstanceState)
    {
        String str = objectofanotherthing.execute("").get();
    }

    class anotherthing extends AsyncTask
    {
        ProgressDialog Dialog;
        protected void onPreExecute()
        {
            Dialog = ProgressDialog.show(context, "Progressing", "Working on it,");
        }

        protected String doInBackground(String... params) 
        {
            ...
        }

        protected void onPostExecute(Integer result)
        { 
            Dialog.dismiss();
        }
    }
}

When I execute my code, my program seems to stop at ProgressDialog.show, no crashes no errors. When I commented this part, the program executes fine. I'm not sure what can be done. Can anyone help me with this. Thanks in advance.

Upvotes: 1

Views: 309

Answers (1)

A--C
A--C

Reputation: 36449

If you call an AsyncTask with get(), you block the UI Thread, and your app can appear to stop responding. Take the get() call out so it is just execute().

objectofanotherthing.execute("");

This means that now your execution is done independently of the UI Thread, so you cannot expect your String to hold anything useful. To get around this, make the AsyncTask a nested class inside your Activity (your snippet does this already), have doInBackground() return something useful, and in onPostExecute() dismiss the dialog and set whatever you need to set.

An alternative to the nested class is passing the Activity off to the AsyncTask or defining an interface, but if the Task is for one activity, nesting is easier.

Upvotes: 2

Related Questions