Jonathan Perkins
Jonathan Perkins

Reputation: 25

Android C# WebView OnPageStart Toast

I am trying to complete an action of some sort while the the WebView is starting, like a loading spinning wheel or a toast message...

What I have done crashes the app. (I'm new to C#, so simple answers are appreciated).

public class MainActivity : Activity
    {
        private static Context context;

        protected override void OnCreate(Bundle bundle)
        {
            base.OnCreate(bundle);



            // Set our view from the "main" layout resource
            SetContentView(Resource.Layout.Main);

            WebView mWebView = FindViewById<WebView>(Resource.Id.webView);
            mWebView.Settings.JavaScriptEnabled = true;

            mWebView.SetWebViewClient(new MyWebViewClient());

            //Load url to be randered on WebView
            mWebView.LoadUrl("https://google.com");


    }


        public class MyWebViewClient : WebViewClient
        {
            public override bool ShouldOverrideUrlLoading(WebView view, string url)
            {
                view.LoadUrl(url);
                return true;
            }

            public override void OnPageStarted(WebView view, string url, Android.Graphics.Bitmap favicon)
            {
                base.OnPageStarted(view, url, favicon);
                Toast.MakeText(context, "Loading...", ToastLength.Short).Show();
            }

            public override void OnPageFinished(WebView view, string url)
            {
                base.OnPageFinished(view, url);
            }

            public override void OnReceivedError(WebView view, ClientError errorCode, string description, string failingUrl)
            {
                base.OnReceivedError(view, errorCode, description, failingUrl);
            }
        }
    }

Upvotes: 1

Views: 638

Answers (1)

matthewrdev
matthewrdev

Reputation: 12170

The private static Context context; field in MainActivity never gets assigned; using it in the Toast.MakeText(context ... ) call will result in a null exception. Fix this by using the global context:

Toast.MakeText(Android.App.Application.Context, "Loading...", ToastLength.Short).Show();

Upvotes: 2

Related Questions