0

I am trying to display a dialog in the onClick method of a TextView. I tested the onClick without the dialog box using a log and it works. When I add the dialogbox to it, like this:

Context context = getApplicationContext();
            Dialog d = new Dialog(context);
            d.setTitle("Test");
            TextView testField = new TextView(context);
            testField.setText("Success!");
            d.setContentView(testField);
            d.show();

This is all in a textView's onClick method. The exception I get says unable to add window -- token null is not for an application.

Can someone please explain to me why this isn't working. I have tons of questions here about getting exceptions in android and the answer always has to do with the order of the code. Is there a reference somewhere about how code should be ordered?!

Thanks!

foobar5512
  • 2,470
  • 5
  • 36
  • 52

2 Answers2

0

Instead of Dialog d = new Dialog(context);

use Dialog d = new Dialog(this);

context obtained from getApplicationContext(); should not be used for dialogs.

For more info, refer question:

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

Community
  • 1
  • 1
Anup Cowkur
  • 20,443
  • 6
  • 51
  • 84
0

When you are creating Dialog in onClick() always use

void onClick(View v)
{
    Dialog d = new Dialog(v.getContext());
                          ^^^^^^^^^^^^^^
    TextView testField = new TextView(v.context);
    testField.setText("Success!");
    d.setContentView(testField);
    d.show();
}
MAC
  • 15,799
  • 8
  • 54
  • 95
  • Thanks! It works! Can you please explain to me what exactly a context is. I looked at it in the documentation but I still don't understand. – foobar5512 Oct 06 '12 at 14:48