Java – Leaked window error for android with progress dialog

Leaked window error for android with progress dialog… here is a solution to the problem.

Leaked window error for android with progress dialog

I’m having trouble displaying a progress dialog with AsyncTask :

Activity has leaked window com.android.internal.policy.PhoneWindow$DecorView{8cee959 V.E...... R...... D 0,0-1026,252} that was originally added here

Here is my asynchronous task:

public class MyClientTask extends AsyncTask<Void, Void, Void> {
    private ProgressDialog progressDialog = null;

private Context mContext;

MyClientTask(Context mContext) {
        this.mContext = mContext;

}

@Override
    protected void onPreExecute() {
        super.onPreExecute();
        progressDialog = new ProgressDialog(mContext);
        progressDialog.setMessage("Working ...");
        progressDialog.setIndeterminate(false);
        progressDialog.setCancelable(false);
        progressDialog.show();
    }

@Override
    protected Void doInBackground(Void... arg0) {
        try {
            wait(5000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return null;
    }

@Override
    protected void onPostExecute(Void result) {
        super.onPostExecute(result);

if (progressDialog != null) {
            progressDialog.dismiss();
            progressDialog = null;
        }

}
}

This is my Activity :

public class ConnectionActivity extends Activity {

final private Context mContext = this;
    private Button buttonConnect;

@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R .layout.activity_socketconnection);

buttonConnect = (Button) findViewById(R.id.buttonConnect);

buttonConnect.setOnClickListener(getConnectOncOnClickListener());
    }

private OnClickListener getConnectOncOnClickListener() {
        return new OnClickListener() {

@Override
            public void onClick(View v) {
                MyClientTask myClientTask = new MyClientTask(mContext);
                try {

myClientTask.execute();
                        myClientTask.get();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } catch (ExecutionException e) {
                    e.printStackTrace();
                }

}
        };
    }

}

I searched for a solution but still it doesn’t work

Solution

Some tips:

  1. Keep a reference to ProgressDialog in your activity and add public methods to show/hide it;

  2. Use WeakReference <Context> in your AsyncTask to let the garbage collector do its job;

  3. Remove myClientTask.get() blocking the UI thread.

Related Problems and Solutions