4

I am showing a toast for already processed items from my utils file.

The scenario I am facing is that if I scan 10 items, and I change my screen, the toasts are still in process and my app crashes with

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

Below is the code that I am using.

In Activity

UtilityMethods.showToast(ActivityName.this, "message"));

In UtilityMethods

public static void showToast(Context c, String s) {
    Toast.makeText(c, s, Toast.LENGTH_SHORT).show();
}

What I tried

I tried adding a try catch block like this:

public static void showToast(Context c, String s) {
    try {
        Toast.makeText(c, s, Toast.LENGTH_SHORT).show();
    }
    catch (WindowManager.BadTokenException e){
        e.printStackTrace();
    }
}

But it is still crashing.

The full exception is below:

Fatal Exception: android.view.WindowManager$BadTokenException: Unable to add window -- token android.os.BinderProxy@321daf0 is not valid; is your activity running?
   at android.view.ViewRootImpl.setView(ViewRootImpl.java:720)
   at android.view.WindowManagerGlobal.addView(WindowManagerGlobal.java:342)
   at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:94)
   at android.widget.Toast$TN.handleShow(Toast.java:459)
   at android.widget.Toast$TN$2.handleMessage(Toast.java:342)
   at android.os.Handler.dispatchMessage(Handler.java:102)
   at android.os.Looper.loop(Looper.java:154)
   at android.app.ActivityThread.main(ActivityThread.java:6123)
   at java.lang.reflect.Method.invoke(Method.java)
   at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:889)
   at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:779)

I also found some other solutions on SO but it did not work.

Please suggest what can be done in my case, thanks in advance.

The Bat
  • 1,085
  • 1
  • 13
  • 31

1 Answers1

0

You are using only this to point to your activity. Make sure this refers to your activity context and not anything else as Toast needs information from the Activity context. Try referring your activity with full name when you are using its context, Try using below code.

UtilityMethods.showToast(YourActivityName.this, "message"));
karan
  • 8,637
  • 3
  • 41
  • 78