Dialog throwing "Unable to add window — token null is not for an application” with getApplication() as context

前端 未结 28 1392
死守一世寂寞
死守一世寂寞 2020-11-22 08:42

My Activity is trying to create an AlertDialog which requires a Context as a parameter. This works as expected if I use:

AlertDialog.Builder builder = new Al         


        
相关标签:
28条回答
  • 2020-11-22 08:48

    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.

    Add the following permission to your manifest:

    <uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW" />
    
    0 讨论(0)
  • 2020-11-22 08:50

    in Activity just use:

    MyActivity.this
    

    in Fragment:

    getActivity();
    
    0 讨论(0)
  • 2020-11-22 08:50

    What worked for me was to pass the activity instead of the context.

    I wanted a custom layout for my dialog, but to keep my code separate, I created it in a separate Class, else I would have to copy and paste that chunk of code into every activity where I want to use the dialog.

    Solution explains my situation but it gives the core solution:

    1. As I was using a ViewAdapter I initialised the adapter with the Activity (not context ex. ->[kotlin] activity: Activity) as a parameter -> ex. [kotlin] this@MainActivity
    2. Then I passed that parameter to the Viewholder
    3. After which passing it again to the class that will inflate the Dialog.

    Use the activity[optional name]: Activity[mandatory type] every where until it gets to the dialog you want to inflate

    Its a lot of passing around, but it does make more sense over copy and pasting the same code everywhere

    0 讨论(0)
  • 2020-11-22 08:54

    Little hack: you can prevent destroying your activity by GC (you should not do it, but it can help in some situations. Don't forget to set contextForDialog to null when it's no longer needed):

    public class PostActivity extends Activity  {
        ...
        private Context contextForDialog = null;
        ...
        public void onCreate(Bundle savedInstanceState) {
            ...
            contextForDialog = this;
        }
        ...
        private void showAnimatedDialog() {
            mSpinner = new Dialog(contextForDialog);
            mSpinner.setContentView(new MySpinner(contextForDialog));
            mSpinner.show();
        }
        ...
    }
    
    0 讨论(0)
  • 2020-11-22 08:54

    adding

    dialog.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ALERT);
    

    and

    "android.permission.SYSTEM_ALERT_WINDOW"/> in manifest

    It works for me now. After even close and open the application, gave me the error at that time.

    0 讨论(0)
  • 2020-11-22 08:54

    If you are using a fragment and using an AlertDialog / Toast message, use getActivity() in the context parameter.

    Worked for me.

    Cheers!

    0 讨论(0)
提交回复
热议问题