sander sander - 22 days ago 9
Java Question

ProgressDialog new Activity Asynctask is not showing, why?

I made a AsyncTask class with the following code

public class removeDialog extends AsyncTask<Void, Void, Void> {

Context c;
ProgressDialog asyncDialog;
String page;

public removeDialog(Context c, String page) {
this.c = c;
this.page = page;

asyncDialog = new ProgressDialog(c);
}

@Override
protected void onPreExecute() {
//set message of the dialog
asyncDialog.setTitle("Please wait");
asyncDialog.setMessage("Loading...");
asyncDialog.setCancelable(false);
//show dialog
asyncDialog.show();

if (page == "algemeneVoorwaarden") {
Intent intent = new Intent(c, algemeneVoorwaarden.class);
c.startActivity(intent);
}
if (page == "contact") {
Intent intent = new Intent(c, contactTest.class);
c.startActivity(intent);
}

super.onPreExecute();
}

@Override
protected Void doInBackground(Void... arg0) {

//don't touch dialog here it'll break the application
//do some lengthy stuff like calling login webservice

return null;
}

@Override
protected void onPostExecute(Void result) {
//hide the dialog
asyncDialog.dismiss();

super.onPostExecute(result);
}
}


First time I tried:
on the first time I see an ProgressDialog, but the second time I want to open the activity I get nothing.

Second time I tried:
I get no ProgressDialog even the first time I try.

I execute my code in an AsyncTask class, code:

voorwaarden.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
new removeDialog(c, "algemeneVoorwaarden").execute();
}
});


Does someone know why it isn't working? Please help me.

Answer

Your dialog will be dismissed as soon as it's shown, because your doInBackground is empty. Try adding a Thread.sleep() with a few seconds, just to simulate a delay.

Also, I suspect that the new activities you're starting will leave your dialog behind. So I would suggest you to test the code without these new activities for now.

public class RemoveDialog extends AsyncTask<Void, Void, Void> {

    ProgressDialog asyncDialog;

    public RemoveDialog(Context c) {
        asyncDialog = new ProgressDialog(c);
    }

    @Override
    protected void onPreExecute() {
        //set message of the dialog
        asyncDialog.setTitle("Please wait");
        asyncDialog.setMessage("Loading...");
        asyncDialog.setCancelable(false);

        //show dialog
        asyncDialog.show();

        super.onPreExecute();
    }

    @Override
    protected Void doInBackground(Void... arg0) {

        try {
            Thread.sleep(3000);
        }
        catch (InterruptedException ex) {
            ex.printStackTrace();
        }

        return null;
    }

    @Override
    protected void onPostExecute(Void result) {
        //hide the dialog
        asyncDialog.dismiss();

        super.onPostExecute(result);
    }
}