2

I have Progress Dialog Class which is singleton

public class ProgressDialogManager {

private static ProgressDialogManager manager = null;

private Context context;

private ProgressDialog pDialog = null;

private ProgressDialogManager(Context context) {
    this.context = context;

}

public static ProgressDialogManager getInstance(Context context) {
    if (manager == null)
        manager = new ProgressDialogManager(context);
    return manager;
}

public void showDialog(String msg) {
    if (pDialog == null)
        pDialog = new ProgressDialog(this.context);
    pDialog.setMessage(msg);
    pDialog.show();
}

public void closeDialog() {
    if (pDialog != null) {
        pDialog.dismiss();
    }
 }
}

when getInstance(this) method multiple activity I get and error

android.view.WindowManager$BadTokenException: Unable to add window — token android.os.BinderProxy@447a6748 is not valid; is your activity running?

my question is Is it Good practice Progress Dialog As Singleton Class and what is the reason of Error how to solved it

Faisal Mohammad
  • 701
  • 8
  • 21
  • It is only good practice when all the other practices are worse. Then it isn't good practice, only the least worst. The reasons are manifold, and best learnt by experience – John May 20 '18 at 10:19

1 Answers1

1

android.view.WindowManager$BadTokenException: Unable to add window

This exception occurs when you are trying to show dialog over an Activity which has been finished and you are passing its context to show the dialog in another Activity.

Your code creates that Scenario:

Suppose you created an instance of ProgressDialogManager in an Activity and shown the dialog in that Activity which would work fine.

Now you destroyed that Activity and moved to another Activity but your previously created ProgressDialogManager instance is not destroyed because you made it singleton. Now if you try to get the instance of ProgressDialogManager it will return previously created ProgressDialogManager and it contains the context of Previous Activity which has been destroyed.

Now if you will try to show the dialog then it will throw this exception because you are trying to show the dialog using dead context.

To solve this problem pass the context also in showDialogand remove the null check on dialog in showDialog.

public void showDialog(String msg, Context context) {
    pDialog = new ProgressDialog(context);
    pDialog.setMessage(msg);
    pDialog.show();
}

Note : Don't make Context as a singleton member of any class because context keeps changing all the time

Ghulam Moinul Quadir
  • 1,448
  • 1
  • 9
  • 16