WindowManager$BadTokenException on toast and activity change

问题: 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...

问题:

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(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.


回答1:

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"));
  • 发表于 2019-01-14 02:52
  • 阅读 ( 317 )
  • 分类:网络文章

条评论

请先 登录 后评论
不写代码的码农
小编

篇文章

作家榜 »

  1. 小编 文章
返回顶部
部分文章转自于网络,若有侵权请联系我们删除