可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
I get the following Android exception when I try to open a dialog. Can someone please help me understand what is going on and how can I fix this problem?
android.view.WindowManager$BadTokenException:
Unable to add window -- token null is not for an application
at android.view.ViewRoot.setView(ViewRoot.java:509)
at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:177)
at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:91)
at android.app.Dialog.show(Dialog.java:241)
回答1:
I'm guessing - are you trying to create Dialog with an application context? Something like this:
new Dialog(getApplicationContext());
This is wrong. You need to use an Activity context.
You have to try like:
new Dialog(YourActivity.this);
回答2:
You can continue to use getApplicationContext()
, but before use, you should add this flag: dialog.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ALERT)
, and the error will not show.
And don't forget to add permission:
<uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW" />
回答3:
In my case I was trying to create my dialog like this:
new Dialog(getApplicationContext());
So I had to change for:
new Dialog(this);
And it works fine for me ;)
回答4:
Try getParent()
at the argument place of context
like new AlertDialog.Builder(getParent());
Hope it will work, it worked for me.
回答5:
I'm guessing - are you trying to create Dialog using.
getApplicationContext()
mContext which is passed by activity.
if You displaying dialog non activity class then you have to pass activity as a parameter.
Activity activity=YourActivity.this;
Now it will be work great.
If you find any trouble then let me know.
回答6:
I got the same exception. what i do to fix this is to pass instance of the dialog
as parameter into function and use it instead of pass only context then using getContext(). this solution solve my problem, hope it can help
回答7:
I tried with this in the context field:
this.getActivity().getParent()
and it works fine for me. This was from a class which extends from "Fragment":
public class filtro extends Fragment{...
回答8:
I got this exception, when I tried to open Progress Dialog under Cordova Plugin by using below two cases,
new ProgressDialog(this.cordova.getActivity().getParent());
new ProgressDialog(this.cordova.getActivity().getApplicationContext());
Later changed like this,
new ProgressDialog(this.cordova.getActivity());
Its working fine for me.
回答9:
Use this and context not worked for me..but MyActivityName.this worked. Hope this helps anyone who need it.