2

I have a problem that I can't solve...

In my Activity, I instantiate a class like this :

MapView mapView = (MapView) findViewById(R.id.mapview);
myMap = new Map(mapView, this);

The constructor looks like this

public Map(MapView mapView, Context context) {
    this.context = context;
    this.mapView = mapView;
}

And what I want to do is to show a progressDialog during a process of this class, so, in Map, I got

private void showPath() {
    progressDialog = ProgressDialog.show(context, "Veuillez patienter", "Calcul de l'itinéraire en cours...", true, false);

    Thread thread = new Thread(this);
    thread.start();
}

When thread is over, I do

progressDialog.dismiss();

This works ! But only one time... If I click on the back button, and re open my activity, I got a BadTokenException

05-06 23:27:15.941: ERROR/AndroidRuntime(1247): android.view.WindowManager$BadTokenException: Unable to add window -- token android.os.BinderProxy@44ecc8e8 is not valid; is your activity running?

I've tryed all solutions I found, but no one works... Even use a class who extends AsyncTask.

Thank you for your help

Moltes
  • 157
  • 1
  • 2
  • 9

1 Answers1

9

As what the error message told you, it's because you try to show a dialog in a Activity but the Activity is not running(have already been finished?). So before you show a dialog, you may want to make sure that the Activity is not finished:

public class MyActivity extends Activity {

    public void showDialog(Dialog dialog) {
        if (!isFinishing()) {
            // If activity is not finished, then show this dialog.
            dialog.show();
        }
    }

}
Tony
  • 1,581
  • 11
  • 24
  • Ok I see, but how can I do this ? The instruction `dialog.show();` is in my class, who isn't an Activity... – Moltes May 07 '11 at 15:48
  • Oh it works ! But I don't know if the way I did it is really good... I've created a private attribute in my class, which is an Activity. I set it in the constructor, and in my method, I do what you told me : `if (!isFinishing()) { // If activity is not finished, then show this dialog. dialog.show(); }` Is it good or not ? – Moltes May 07 '11 at 16:12
  • If the object of your class which keeps an reference to an Activity is not a long-lived object, then it's okay to do that. Read [this article](http://developer.android.com/resources/articles/avoiding-memory-leaks.html) about avoiding memory leaks in Android document for more explanation. – Tony May 08 '11 at 03:02