Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

what belong is BadTokenException at classes of project

I am trying to run my app in API 25 but when I tap button I got this error:

E/ACRA: ACRA caught a BadTokenException for com.safa.visit.ts.debug
    android.view.WindowManager$BadTokenException: Unable to add window -- token android.os.BinderProxy@2fc535e is not valid; is your activity running?
        at android.view.ViewRootImpl.setView(ViewRootImpl.java:922)
        at android.view.WindowManagerGlobal.addView(WindowManagerGlobal.java:377)
        at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:105)
        at android.widget.Toast$TN.handleShow(Toast.java:747)
        at android.widget.Toast$TN$2.handleMessage(Toast.java:622)
        at android.os.Handler.dispatchMessage(Handler.java:102)
        at android.os.Looper.loop(Looper.java:154)
        at android.app.ActivityThread.main(ActivityThread.java:6823)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1563)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1451)
Disconnected from the target VM, address: 'localhost:8600', transport: 'socket'

I have searched and I find out this problem is for Toast. Because toast context may be be NULL. For that I checked context before showing context. This is my method:

    private void toastError(Context ctx,final String msg) {
    if (ctx != null)
    Toast.makeText(ctx, msg, Toast.LENGTH_SHORT).show();
}

My problem is, I do not know this error is for what page or class, because that place, where I clicked at the button and this error is appeared, I put my method there and have used my method instead of Toast but still I got this error.

What can you suggest me?

like image 789
Cyrus the Great Avatar asked Jan 18 '26 05:01

Cyrus the Great


2 Answers

I have created a library to hook and fix this BadTokenException:

https://github.com/drakeet/ToastCompat

Just use:

ToastCompat.makeText(context, "hello world!", Toast.LENGTH_SHORT).show();

Or with BadTokenListener#onBadTokenCaught(@NonNull Toast toast):

ToastCompat.makeText(this, "hello", Toast.LENGTH_SHORT)
    .setBadTokenListener(toast -> {
        ...
    }).show();

Why the Exception: https://github.com/drakeet/ToastCompat#why

like image 127
drakeet Avatar answered Jan 19 '26 19:01

drakeet


Try:

if(!((Activity) context).isFinishing())
{
     Toast.makeText(ctx, msg, Toast.LENGTH_SHORT).show();
}
like image 40
lkatiforis Avatar answered Jan 19 '26 20:01

lkatiforis