Popupwindow $Badtokenexception: Unable to Add Window -- Token Null Is Not Valid

Unable to add window -- token null is not valid; is your activity running?

I had the same problem as you, it looks like you used the tutorial from http://www.piwai.info/chatheads-basics like I did. The problem is that you cannot reliably pass the current activity to the popup window, because you have no control over the current activity. It looks like there might be a unreliable way to get the current activity, but I don't recommend that.

The way I fixed it for my app was to not use the popup window, but instead make my own through the window manager.

private void showCustomPopupMenu()
{
windowManager2 = (WindowManager)getSystemService(WINDOW_SERVICE);
LayoutInflater layoutInflater=(LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view=layoutInflater.inflate(R.layout.xxact_copy_popupmenu, null);
params=new WindowManager.LayoutParams(
WindowManager.LayoutParams.WRAP_CONTENT,
WindowManager.LayoutParams.WRAP_CONTENT,
WindowManager.LayoutParams.TYPE_PHONE,
WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE,
PixelFormat.TRANSLUCENT
);

params.gravity=Gravity.CENTER|Gravity.CENTER;
params.x=0;
params.y=0;
windowManager2.addView(view, params);
}

If you want this to look like a popup window, just add a transparent gray view as the background and add a onClickListener to it to remove the view from the windowManager object.

I know this isn't as convenient as a popup, but from my experience, it is the most reliable way.

and don't forget to add permission in your manifest file

<uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW"/>

PopupWindow $BadTokenException: Unable to add window -- token null is not valid

you are showing your popup too early. You may post a delayed runnable for showatlocation in Onresume , Give it a try

Edit:
This post seems to have the same problem answered Problems creating a Popup Window in Android Activity

In AlertDialog - Unable to add window -- token null is not valid; is your activity running?

  1. Pass the current activity context instead Application context in AlertDialog.Builder().
  2. Set the AlertDialog type to WindowManagerTypes.ApplicationPanel intead of Toast
AlertDialog.Builder builder = new AlertDialog.Builder(context);//current activity.
b.Window.SetType(WindowManagerTypes.ApplicationPanel);

$BadTokenException: Unable to add window -- token null is not for an application - Kotlin

It causes error, because it can't find the current view's context to show the AlertDialog

So what you need to do is replacing val context = applicationContext to

val context = view.context


Related Topics



Leave a reply



Submit