Kai Kai - 3 months ago 49
Android Question

Android: ProgressDialog not showing in AsyncTask called in onCreate()

I have a AsyncTask which will be executed in the

onCreate
method. However, my ProgressDialog isn't showing up. And from debugging, it is confirmed that the AsyncTask is being executed.

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_lifestyle);
context = getApplicationContext();

new testAsync().execute();
}

private class testAsync extends AsyncTask<Void,Void,Void> {
private ProgressDialog pDialog;

@Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(MainActivity.this); // tried with context, no difference
pDialog.setTitle("Inserting sample data");
pDialog.setMessage("Please wait. This dialog will be dismissed upon completion.");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}

@Override
protected Void doInBackground(Void... params) {
// TableControllerReadings TCR = new TableControllerReadings(context);
// TCR.insertSampleData(getApplicationContext());

new Timer().schedule(new TimerTask() {
@Override
public void run() {
//delay for 5 seconds
}
}, 5000);

return null;
}

@Override
protected void onPostExecute(Void v) {
pDialog.dismiss();
}
}

Answer

Take your pDialog.dismiss(); into the your timer thread.

Reason: onPostExecute() immediately call because on background task is finished.

Its seprate thread which is on delay so cursor move to the onPostExecute()

 private class testAsync extends AsyncTask<Void, Void, Void> {
        private ProgressDialog pDialog;

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            pDialog = new ProgressDialog(MainActivity.this); // tried with context, no difference
            pDialog.setTitle("Inserting sample data");
            pDialog.setMessage("Please wait. This dialog will be dismissed upon completion.");
            pDialog.setIndeterminate(false);
            pDialog.setCancelable(false);
            pDialog.show();
        }

        @Override
        protected Void doInBackground(Void... params) {
            //  TableControllerReadings TCR = new TableControllerReadings(context);
            //  TCR.insertSampleData(getApplicationContext());

            new Timer().schedule(new TimerTask() {
                @Override
                public void run() {
                    //delay for 5 seconds
                    pDialog.dismiss();
                }
            }, 5000);

            return null;
        }

        @Override
        protected void onPostExecute(Void v) {
         // pDialog.dismiss();
        }
    }
Comments