0

I get this error every once in a while and not sure how to fix it. I read that the context could be destroyed but no REAL answers on how to solve it, especially for my situation. The error happens below on Utility.showDialog in the onPostExecute on my BaseLoadOperation. What is the correct way to handle this?

DataTask.java

public class DataTask extends BaseLoadOperation {

    public DataTask(Context context) {
        super(context);
    }
        @Override
            protected void onPostExecute(Object result) {
                super.onPostExecute(result);
                Utility.showDialog(this.context.getString(R.string.connectionerror), "OK", this.context);
            }

Utility.java

public static void showDialog(String message, String buttonText, Context context, final IDialogCallback callback) {
        AlertDialog.Builder builder = new AlertDialog.Builder(context);
        builder.setMessage(message)
               .setCancelable(true)
               .setPositiveButton(buttonText, new DialogInterface.OnClickListener() {
                   public void onClick(DialogInterface dialog, int id) {
                       if(callback != null)
                       {
                           callback.buttonPress();
                       }
                   }
               });
        AlertDialog alert = builder.show();
        TextView messageText = (TextView)alert.findViewById(android.R.id.message);
        messageText.setGravity(Gravity.CENTER);

        alert.show();
    }

Exception android.view.WindowManager$BadTokenException: Unable to add window -- token android.os.BinderProxy@49fff91 is not valid; is your activity running?

android.view.ViewRootImpl.setView (ViewRootImpl.java:900)
android.view.WindowManagerGlobal.addView (WindowManagerGlobal.java:342)
android.view.WindowManagerImpl.addView (WindowManagerImpl.java:97)
android.app.Dialog.show (Dialog.java:419)
android.support.v7.app.AlertDialog$Builder.show (AlertDialog.java:956)
com.exposure.utilities.Utility.showDialog (Utility.java:196)
com.exposure.utilities.Utility.showDialog (Utility.java:181)
com.exposure.utilities.DataTask.onPostExecute (DataTask.java:44)
Mike Flynn
  • 21,905
  • 50
  • 167
  • 308
  • Have you [read here](https://stackoverflow.com/a/18665887/2910520)? – MatPag Jun 19 '17 at 20:39
  • I didnt see that one but I see the isFinishing(). Does this just not show a dialog at all? Isnt the point to show the dialog if possible? – Mike Flynn Jun 19 '17 at 20:44
  • If the Acitivity is finishing the Context cannot be used anymore to open a dialog. The best thing you could do (IMO) could be a callback in `onPostExecute(...)` which trigger some code in your Activity. Then inside that callback checking if Activity is finishing before proceeding to call `Utility.showDialog(...)` – MatPag Jun 19 '17 at 20:54
  • Or just catch the exception – Martin De Simone Jun 19 '17 at 21:48

0 Answers0