Why new AlertDialog.Builder (getApplicationContext ()). create () does not work?

3

I have been observing this problem for some time, and I always have to keep an instance of Activity current, instead of just keeping an instance of Context , and until then I did not understand why, since the method AlertDialog.Builder(Context context) , requires as an initialization parameter only one instance of Context and not Activity .

So if I make the following code:

AlertDialog alert = new AlertDialog.Builder(getApplicationContext()).create();
alert.setTitle("Title");
alert.setMessage("Message");
alert.show();

The following running error is generated:

04-22 13:06:55.585: E/AndroidRuntime(3014): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.appteste/com.example.appteste.MainActivity}: android.view.WindowManager$BadTokenException: Unable to add window -- token null is not for an application

If I pass Activity as a parameter instead of Context , everything works as expected:

AlertDialog alert = new AlertDialog.Builder(this).create();
alert.setTitle("Title");
alert.setMessage("Message");
alert.show();

I tested the following versions of Android: 4.0.3 and 4.4.2

My doubts are as follows:

  • Is this an Android problem?
  • Am I doing something wrong?
  • Why does this happen?
  •   

    Note: For test purposes, the codes presented were executed within the onCreate(Bundle savedInstanceState) method of Activity .

        
    asked by anonymous 22.04.2014 / 19:30

    3 answers

    3

    1 - Is this an Android problem?

    Apparently no: getApplicationContext() should be used if you need a context whose lifecycle is separate from the current context, which is linked to the process lifetime rather than the current component. More details in the documentation.

    2 - Am I doing something wrong?

    Probably yes: So since you are using Activity and creating your AlertDialog within it, the context of this alert will be your activity. Based on this answer.

    3 - Why does this happen?

    The rationale is that AlertDialog does not have a life outside its Activity .

    So it needs the context in which it was created, as getApplicationContext () is different from this of your activity you will have this Exception .

        
    22.04.2014 / 22:50
    -1

    This is an example of an AlertDialog.

    AlertDialog.Builder ADBuilder = new AlertDialog.Builder(MainActivity.this);
    ADBuilder.setIcon(R.drawable.ic_dialog_info);
    ADBuilder.setTitle("TÍTULO DO ALERTA");
    ADBuilder.setMessage("MENSAGEM DO ALERTA");
    ADBuilder.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int which) {
            // CÓDIGO QUE SERÁ EXECUTADO SE O USUÁRIO PRESSIONAR O BOTÃO SIM
        }
    });
    ADBuilder.setNegativeButton(android.R.string.no, new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int which) {
            // CÓDIGO QUE SERÁ EXECUTADO SE O USUÁRIO PRESSIONAR O BOTÃO NÃO
        }
    });
    ADBuilder.show();
    
        
    23.04.2014 / 17:01
    -1

    As far as I know, there is no getApplicationContext() or it does not apply to AlertDialog.Builder . Try to use this minimized code made by me:

    AlertDialog.Builder(this)
        .create()
        .setTitle("titulo")
        .setMessage("msg")
        .setPositiveButton("funcao 1",
                           new DialogInterface.OnClickListener()
           {
              @Override public void onClick(DialogInterface _dialog, int _which)
              {
                 //codigo
              }
           })
        .show();
    
        
    19.12.2018 / 16:32