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

前端 未结 28 1286
死守一世寂寞
死守一世寂寞 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 09:01

    In Activity on click of button showing a dialog box

    Dialog dialog = new Dialog(MyActivity.this);
    

    Worked for me.

    0 讨论(0)
  • 2020-11-22 09:01

    Use MyDialog md = new MyDialog(MyActivity.this.getParent());

    0 讨论(0)
  • 2020-11-22 09:02

    Using this did not work for me, but MyActivityName.this did. Hope this helps anyone who could not get this to work.

    0 讨论(0)
  • 2020-11-22 09:03

    Instead of getApplicationContext(), just use ActivityName.this.

    0 讨论(0)
  • 2020-11-22 09:03

    I had to send my context through a constructor on a custom adapter displayed in a fragment and had this issue with getApplicationContext(). I solved it with:

    this.getActivity().getWindow().getContext() in the fragments' onCreate callback.

    0 讨论(0)
  • 2020-11-22 09:03

    Just use following:

    FOR JAVA USERS

    In case you are using activity --> AlertDialog.Builder builder = new AlertDialog.Builder(this);

    OR

    AlertDialog.Builder builder = new AlertDialog.Builder(your_activity.this);

    In case you are using fragment --> AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());

    FOR KOTLIN USERS

    In case you are using activity --> val builder = AlertDialog.Builder(this)

    OR

    val builder = AlertDialog.Builder(this@your_activity.this)

    In case you are using fragment --> val builder = AlertDialog.Builder(activity!!)

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