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?
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
Try:
if(!((Activity) context).isFinishing())
{
Toast.makeText(ctx, msg, Toast.LENGTH_SHORT).show();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With