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

Asked

Viewed 1,285 times

3

I have been observing this problem for some time, and I always have to maintain an instance to Activity current, rather than maintaining only one instance to Context, and until then did not understand why, since the method AlertDialog.Builder(Context context), requires only one instance of Context and not of 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 error running 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

Already if I pass the 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 in the following versions of Android: 4.0.3 and 4.4.2

My doubts are as follows:

  1. This is a problem (Bug) of Android?
  2. I’m doing something wrong?
  3. Why does this happen?

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

  • 1

    This is another of several that Android has. You’re not doing anything wrong, as long as you pass an Activity Context. This reminds me of that phrase from Ford: "You can choose any color for the car, as long as it’s black!"

  • @ramaral, so there’s nothing a programmer can do? Android is asking for a Context, but actually he wants a Activity, is that what you meant right? And I’ll have to keep an instance of Activity where I intend to call a AlertDialog, without certain crying?

  • From the little research I’ve done, there’s nothing we can do. Activity is a Context such as Applicationcontext, but it seems that Alertdialog needs more than a simple Context, it needs something that Activity adds. Read this

  • @Ramaral, reading a little bit more, seems to me to be more confusing than at the beginning, because hell, they made a structure that way. I believe, that if this is an Android bug, it is a horrible Designer error, because it makes it difficult to understand a structure that could be much simpler, and a gap for bugs, because any inattentive developer (like me) can create a code that passes a Context, and if it doesn’t get caught up in the tests, it might blow up in the end user. I don’t understand why this choice by the Android developers.

3 answers

3


1 - This is a problem (Bug) of Android?

Apparently not: getApplicationContext() should be used if you need a context whose life cycle is separated from the current context , which is linked to the process life time rather than the current component. More details in the documentation.

2 - I’m doing something wrong?

Probably yes: So how are you using one Activity and creating their AlertDialog within it, the context of that Alert will be your Activity. Based on this answer.

3 - Why does this happen?

The reasoning is that the AlertDialog doesn’t have a life outside of his Activity.

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

-1

As far as I know, there is no getApplicationContext() or shall 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();

-1

This is an example of a 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();
  • Jhonas, thank you for your attention, but my doubt is not how to create a AlertDialog, but yes on the problem(bug), when passing the getApplicationContext() as a parameter instead of Activity.

  • 1

    @Jhonaskenneboeno avoid simply posting the code. Even though it has already been reported as insufficient for the question, elaborate a response itself, detailing processes, commenting on the script and everything else that is deemed necessary is of great value to the community because, today, it may serve no one, but tomorrow or later, some user brought in by Google may have their question answered before they even asked her.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.