1

I started developing Android apps today using Visual Studio 2015 and I'd like to know why I can't show an AlertDialog, because it throws me an exception about Android.Views.WindowManagerBadTokenException and I don't see where I'm mistaken..

private void Button_Click(object sender, EventArgs e)
{
    ((Button)sender).Text = string.Format("{0} clicks!", count++);
    try
    {
        AlertDialog.Builder builder = new AlertDialog.Builder(this.ApplicationContext);
        builder.SetTitle("This is a title..");
        builder.SetMessage("This is a message..");
        AlertDialog ad = builder.Create();
        ad.Show();
    }
    catch (Exception ex)
    { ((Button)sender).Text = ex.Message; }
}
Omer Aviv
  • 286
  • 3
  • 20
  • 1
    `this.ApplicationContext` why? why don't you use `this` directly? – njzk2 Jul 30 '15 at 15:06
  • I thought I gotta send the `ApplicationContext` because it requests a Context in the constructor.. – Omer Aviv Jul 30 '15 at 15:42
  • for some reason, alertdialog requests a context, but will only work with an activity context (nice design, android...). You need an activity here. (`this` is probably an activity, isn't it?) – njzk2 Jul 30 '15 at 15:55

1 Answers1

0

First of all, if you just started developing for Android, USE ANDROID STUDIOS unless you have a really really good reason to develop in Visual Studios. Android Studios is the best IDE I've ever used and I highly recommend it.

But, if you would like to stick with Visual Studios, try this code:

AlertDialog alertDialog = new AlertDialog.Builder(MainActivity.this).create();
alertDialog.setTitle("Alert");
alertDialog.setMessage("Alert message to be shown");
alertDialog.setButton(AlertDialog.BUTTON_NEUTRAL, "OK",
    new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int which) {
            dialog.dismiss();
        }
    });
alertDialog.show();

Pulled from this question. Maybe it's because your .Create() and .Show() should be all lower case instead of camel case.

Community
  • 1
  • 1
SMKS
  • 991
  • 12
  • 21
  • 1
    `new AlertDialog.Builder(this)` worked for me as njzk2 said. – Omer Aviv Jul 30 '15 at 15:49
  • Oh alright, awesome. But seriously, in [Android Studios](https://developer.android.com/sdk/index.html) it would have found that error in no time at all. I highly recommend it. – SMKS Jul 30 '15 at 15:51