0

I used to create it like this

        AlertDialog.Builder b = new AlertDialog.Builder( Forms.Context );

And it worked fine. But Forms.Context is obsolete now so I changed it to

        AlertDialog.Builder b = new AlertDialog.Builder( Android.App.Application.Context );

Now it crashes with

Android.Content.Res.Resources+NotFoundException: Resource ID #0x0

I tried the alternative constructor

        AlertDialog.Builder b = new AlertDialog.Builder( Android.App.Application.Context, Resource.Style.Theme_AppCompat_Light );

And that crashes with

Android.Views.WindowManagerBadTokenException: Unable to add window -- token null is not for an application

So what context do I pass to AlertDialog.Builder() in XF2.5? I don't feel like installing a 3rd party library for this.

Vadim Kotov
  • 8,084
  • 8
  • 48
  • 62
Anton Duzenko
  • 2,366
  • 1
  • 21
  • 26

1 Answers1

2

One way is to create a static variable in Main Activity like this

public class MainActivity : global::Xamarin.Forms.Platform.Android.FormsAppCompatActivity
{
    internal static MainActivity Instance { get; private set; }

    protected override void OnCreate(Bundle bundle)
    {
        ...
        global::Xamarin.Forms.Forms.Init(this, bundle);
        Instance = this;
        LoadApplication(new App());
    }
}

The reference it in your code like this

AlertDialog.Builder b = new AlertDialog.Builder( MainActivity.Instance );

For more details and other ways to achieve this, see David Britchs blog post

Steve Chadbourne
  • 6,873
  • 3
  • 54
  • 82
  • 1
    Quote from your link: "Xamarin.Forms.Forms.Context has been marked obsolete because it was a global static reference to an Activity, which is not ideal." So what is the benefit of replacing one global static with another? – Anton Duzenko Dec 06 '17 at 11:55
  • 1
    @AntonDuzenko XF did that because with the old way, you can't be sure if the context was from MainActivity. With this approach, when you want to use Instance, you specify MainActivity.Instance. It seems obvious you target MainActivity and not SplashscreenActivity for instance. You can find more here : https://stackoverflow.com/questions/47353986/xamarin-forms-forms-context-is-obsolete – Nk54 Jan 02 '19 at 18:09