Ron
Ron

Reputation: 2019

Dismissing ProgessDialog on Android

I've been to get rid of a ProgressDialog for some time now. After some googling and reading through questions on stackoverflow I round that I can only run ProgressDialog.dismiss() from the UI Thread. After some more reading I learned I need to create a handler and attach it to the UI Thread like this: new Handler(Looper.getMainLooper()); but alas, the stubborn ProgressDialog still refuses to die.

Here's what my code looks like:

/* Members */
private ProgressDialog mProgressDialog;
private Handler mHandler;

/* Class' constructor method */
public foo() {
    ...
    this.mHandler = new Handler(Looper.getMainLooper());
    ...
}

/* The code that shows the dialog */
public void startAsyncProcessAndShowLoader(Activity activity) {
    ...
    mProgressDialog = new ProgressDialog(activity, ProgressDialog.STYLE_SPINNER);
    mProgressDialog.show(activity, "Loading", "Please wait...", true, false);
    doAsyncStuff(); // My methods have meaningful names, really, they do
    ...
}

/* After a long process and tons of callbacks */
public void endAsyncProcess() {
    ...
    mHandler.post(new Runnable() {
        @Override
        public void run() {
            Log.d(TAG, "Getting rid of loader");
            mProgressDialog.dismiss();
            mProgressDialog = null;
            Log.d(TAG, "Got rid of loader");
        }
    });
    ...
}

This doesn't seem to work, debugging shows that certain members of the PorgressDialog (mDecor) are null. What am I missing?

Upvotes: 0

Views: 422

Answers (3)

happyhls
happyhls

Reputation: 121

Try this:

public static final int MSG_WHAT_DISMISSPROGRESS = 100;
Handler handler = new Handler(){
    @Override
    public void handleMessage(Message msg){
        swtich(msg.what){
            case MSG_WHAT_DISMISSPROGRESS:
                mProgressDialog.dismiss();
            break;
        }
    }
}

public void endAsyncProcess(){
    handler.obtainMessage(MSG_WHAT_DISMISSPROGRESS).sendToTarget();
}

Upvotes: 0

flx
flx

Reputation: 14226

You should use the AsyncTask to do your async task:

AsyncTask task = new AsyncTask<Void, Void, Void>() {
    private Dialog mProgressDialog;

    protected void onPreExecute() {
        mProgressDialog = new ProgressDialog(activity, ProgressDialog.STYLE_SPINNER);
        mProgressDialog.show(activity, "Loading", "Please wait...", true, false);
    }

    protected Void doInBackground(Void... param) {
        doAsyncStuff(); // My methods have meaningful names, really, they do
        return null;
    }

    protected void onPostExecute(Void result) {
        mProgressDialog.dismiss();
    }
};
task.execute(null);

Upvotes: 1

Dyna
Dyna

Reputation: 2305

progressDialog.setCancelable(true);
progressDialog.setOnCancelListener(new OnCancelListener() {

    public void onCancel(DialogInterface dialog) {
    Log.d(TAG, "Got rid of loader");
    }
});

Upvotes: 0

Related Questions