2

I use asynctask quite often however this time it doesn't work! I have a UI contains a viewpager and fragments. To populate the view, it takes about 3 secs. Now I want to show the ProgressDialog until it finishes by using AsyncTask. But the ProgressDialog is not showing!!!!

Anybody can tell me the solution? Thanks

onCreate(...){
   setContentView(...)
   new LoadUI(MyActivity.this).execute();
}

public class LoadUI extends AsyncTask<Void, Void, Void>{
    ProgressDialog pd;
    Context context;

    public LoadUI(Context mContext) {
        this.context = mContext;
        pd = new ProgressDialog(mContext);
        aViewPager = (ViewPager) findViewById(R.id.aPagerDay);
    }

    @Override
    protected void onPreExecute() {
        pd.show();
    }

    @Override
    protected Void doInBackground(Void... params) {
        //Create ViewPager
        //Create pagerAdapter
        return null;
    }

    @Override
    protected void onPostExecute(Void result) {
        if (pd.isShowing()) {
            pd.dismiss();
        }
        super.onPostExecute(result);
    }

}
T D Nguyen
  • 7,054
  • 4
  • 51
  • 71

2 Answers2

0

You can try out two options:

Either use the AsyncTask's method get(long timeout, TimeUnit unit) like that:

task.get(1000, TimeUnit.MILLISECONDS);

This will make your main thread wait for the result of the AsyncTask at most 1000 milliseconds.

Alternatively you can show a progress dialog in the async task until it finishes. See this thread. Basically a progress dialog is shown while the async task runs and is hidden when it finishes.

You have even third option:" if Thread is sufficient for your needs you can just use its join method. However, if the task is taking a long while you will still need to show a progress dialog, otherwise you will get an exception because of the main thread being inactive for too long.

Community
  • 1
  • 1
GrIsHu
  • 29,068
  • 10
  • 64
  • 102
0

The problem is the GUI is not ready in onCreate(). And nothing will be shown if I try to show Dialog in this state. A solution is move the dialog to activity onStart():

@override
onStart(){
   new LoadUI(MyActivity.this).execute();
}
T D Nguyen
  • 7,054
  • 4
  • 51
  • 71