Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dismiss dialog after screen orientation change

Tags:

android

1) I launch a background task (via AsyncTask)

new FindJourneyTask().execute(); // FindJourneyTask extends AsyncTask

2) Still in the main thread (just before new thread is launched) I create a dialog with showDialog(dialogId)

// this method is in FindJourneyTask
protected void onPreExecute() {
    showDialog(DIALOG_FINDING_JOURNEY);
}

3) Screen orientation changes and the Activity is recreated

4) How can I now dismiss the dialog from the FindJourneyTask? Calling dismissDialog(dialogId) does nothing.

// this method is in FindJourneyTask
protected void onPostExecute(FindJourneyResult result) {
    dismissDialog(DIALOG_FINDING_JOURNEY); // does nothing
}
like image 531
fhucho Avatar asked Feb 26 '10 18:02

fhucho


1 Answers

This is a common problem, and there are no real good solutions. The issue is that on screen orientation change, the entire Activity is destroyed and recreated. At the same time, the Dialog you previously had is re-created in the new Activity, but the old background task still refers to the old Activity when it tries to dismiss the dialog. The result is that it dismisses a dialog which was long ago destroyed, rather than dismissing the dialog the new orientation created.

There are three basic solutions:

  1. Override the default orientation-handling code so that your Activity is not destroyed upon rotation. This is probably the least satisfactory answer, as it blocks a lot of code that is automatically run upon orientation changes.

  2. Create a static member variable of your Activity that references the Activity itself, so you can call STATIC_ACTIVITY_VARIABLE.dismissDialog().

  3. Code a solution in which the background task keeps track of the current Activity and updates itself as necessary.

These three solutions are discussed at length here: http://groups.google.com/group/android-developers/browse_thread/thread/bf046b95cf38832d/

like image 52
Dan Lew Avatar answered Oct 02 '22 14:10

Dan Lew