tags:

views:

21

answers:

0

I have an activity that loads an AlertDialog like this.

        progressDialog = new ProgressDialog( MyActivity.this );
        progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
        progressDialog.setMessage("Doing Something");
        progressDialog.setCancelable(false);
        progressDialog.show();

I also have another class that extends AsyncTask

    private class MyBackgroundTask extends AsyncTask<Void, Void, Boolean> {

        @Override
        protected Boolean doInBackground(Void... params) {

            ...do stuff
        }

        @Override
        protected void onPostExecute(Boolean result) {

            progressDialog.dismiss();
        }

        @Override
        protected void onProgressUpdate(Void... values) {

        }

    }

If the orientation of the screen changes I get an error about trying to attach to a view that does not exist. This is because the Activity has been destroyed and the context has gone away.

So I added this to onDestroy() and it fixed it.

    @Override
    public void onDestroy() {

        if(progressDialog!=null)
            if(progressDialog.isShowing())
                progressDialog.cancel();

        if(background!=null)
            background.cancel(true);
    }

But this means that I always have to keep a reference to the Dialog and AsyncTask

So I cant do this for example:

new MyAsyncTask().execute();

In case the orientation changes, equally I can't do this:

    new AlertDialog.Builder(this)
    .setIcon(android.R.drawable.ic_dialog_alert)
    .setTitle( "some title" )
    .setMessage("some message")
    .setPositiveButton(R.string.ok, null)
    .show();

This does not seem right to me and there must be a better way, I know you can use getApplicationContext() but in some situations this is not viable.

How do I manage this properly?