Android C# WebView OnPageStart Toast - c#

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);
}
}
}

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();

Related

Return Back to app from browser Xamarin.Android

I have a button in my mainactivity,after clicking it,it opens a new activity(Acitivity2).
And in that activity I am opening the browser.Here are the codes-
public class Activity2 : Activity
{
protected override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
this.OpenBrowser();
}
public void OpenBrowser()
{
var uri = Android.Net.Uri.Parse("https://google.com");
var intent = new Intent(Intent.ActionView, uri);
intent.AddFlags(ActivityFlags.NoHistory)
.AddFlags(ActivityFlags.NewTask);
Application.Context.StartActivity(intent);
}
protected override void OnNewIntent(Intent intent)
{
base.OnNewIntent(intent);
}
}
Now my question is after successful completion of opening the url in the browser,how to go back to the app,currently browser never closes.
Sorry it may be simple question,but i am really struggling with it

Progressbar while loading webview in xamarin android

I want to show a progressbar while the webview gets loaded and hide the progessbar when the webview gets loaded completely.
Here is my Activity.cs
progress = new ProgressDialog(this);
progress.Indeterminate = true;
progress.SetProgressStyle(Android.App.ProgressDialogStyle.Spinner);
progress.SetMessage("Loading... Please wait...");
progress.SetCancelable(false);
progress.Show();
_faq = FindViewById<Android.Webkit.WebView>(Resource.Id.wv_FAQ);
_web.AppWebViewClients(progress);
_web.ShouldOverrideUrlLoading(_faq, _url);
_web.OnPageFinished(_faq, _url);
here is my ResourceWebView.cs
public class ResourceWebView: WebViewClient
{
Android.App.ProgressDialog progress;
public void AppWebViewClients(ProgressDialog progressBar)
{
this.progress = progressBar;
progress.Show();
}
public bool ShouldOverrideUrlLoading(WebView view, String url)
{
view.LoadUrl(url);
progress.Show();
return true;
}
public void OnPageFinished(WebView view, String url)
{
OnPageFinished(view, url);
progress.Hide();
}
}
But this code is not work for me..
Try this
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_web_view);
urlEditText = (EditText) findViewById(R.id.urlField);
webView = (WebView) findViewById(R.id.webView);
webView.setWebViewClient(new MyWebViewClient());
progress = (ProgressBar) findViewById(R.id.progressBar);
progress.setVisibility(View.GONE);
Button openUrl = (Button) findViewById(R.id.goButton);
openUrl.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view) {
String url = urlEditText.getText().toString();
if (validateUrl(url)) {
webView.getSettings().setJavaScriptEnabled(true);
webView.loadUrl(url);
}
}
private boolean validateUrl(String url) {
return true;
}
});
}
private class MyWebViewClient extends WebViewClient {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
#Override
public void onPageFinished(WebView view, String url) {
progress.setVisibility(View.GONE);
WebViewActivity.this.progress.setProgress(100);
super.onPageFinished(view, url);
}
#Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
progress.setVisibility(View.VISIBLE);
WebViewActivity.this.progress.setProgress(0);
super.onPageStarted(view, url, favicon);
}
}
Reference this for more reference : http://stacktips.com/tutorials/android/progressbar-while-loading-webview

Non-static field, method, or property

Looking at this How to show loading image or progress bar on WebView it clearly says that the following approach should work but I am having an issue as I cannot access my ProgressBar in public override void OnPageFinished(WebView view, string url)
My Code is the following
webView.Settings.JavaScriptEnabled = true;
webView.Settings.LoadWithOverviewMode = true;
webView.Settings.UseWideViewPort = true;
webView.SetWebViewClient(new WebViewClientClass());
webView.LoadDataWithBaseURL("file:///android_asset/", HTML_DATA, "text/html", "UTF-8", null);
Where my WebViewClientClass is the following
#region Webview URL handler
internal class WebViewClientClass : WebViewClient
{
public override bool ShouldOverrideUrlLoading(WebView view, IWebResourceRequest request)
{
Android.Net.Uri url = request.Url;
view.LoadUrl(url.ToString());
return true;
}
public override void OnPageStarted(WebView view, string url, Bitmap favicon)
{
base.OnPageStarted(view, url, favicon);
Log.Info("101028", "loading started");
}
public override void OnPageFinished(WebView view, string url)
{
base.OnPageFinished(view, url);
Log.Info("101028", "loading finised");
PB.Visibility = ViewState.Gone; ***<<<<<<<------ ERROR HERE***
}
}
#endregion
I can see the results in logcat but when I try to access my ProgressBar such as PB.Visibility = ViewState.Gone in OnPageFinished method - I get the following error
ERROR
An object reference is required for the non-static field, method, or property
PogressBar Code
private ProgressBar PB;
protected override async void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
SetContentView(Resource.Layout.Read);
PB = FindViewById<ProgressBar>(Resource.Id.MyProgressBar);
}
Anyone knows what is the right approach for this? How do i make this work
Cheers
From your code it seems that your ProgressBar belongs to your Activity and you are trying to access it in WebViewClientClass that's why your object reference is missing.
So you should have a method inside your activity class which will hide/show ProgressBar and there must be some kind of call back mechanism to call this method
Define an interface like below
interface ProgressBarHandler{
public void hideProgress();
}
And in your activity class implement this interface
class MyActivity extends Activity implements ProgressBarHandler{
//other usual things in your activity
protected override async void OnCreate(Bundle savedInstanceState){
//here pass the activity instance to WebViewClientClass
webView.SetWebViewClient(new WebViewClientClass(this));
}
public void hideProgress(){
PB.Visibility = ViewState.Gone;
}
}
AND finally in your WebViewClientClass
class WebViewClientClass : WebViewClient
{
private ProgressBarHandler handler;
public WebViewClientClass(ProgressBarHandler handler){
this.handler = handler;
}
public override void OnPageFinished(WebView view, string url)
{
base.OnPageFinished(view, url);
Log.Info("101028", "loading finised");
handler.hideProgress();
}
}

Getting System.InvalidCastException in c#

I'm trying to access global activity variables (which I can't make as static) from a BroadcastReceiver . For that, I create a instance of the activity this way:
class wifiReceiver : BroadcastReceiver
{
public override void OnReceive(Context context, Intent intent)
{
MainActivity activity = (MainActivity)context.ApplicationContext;
...
But i get System.InvalidCastException: Specified cast is not valid. in instance creation line. What am i doing wrong?
EDIT: Some code of my activity
public class MainActivity : Activity
{
private WifiManager _manager;
private List<string> _wifiSignals;
private wifiReceiver _wifiReceiver;
private TextView _Text;
protected override void OnCreate(Bundle bundle)
{
...
_wifiReceiver = new wifiReceiver();
_manager = (WifiManager)GetSystemService(Context.WifiService);
_wifiSignals = new List<string>();
if (_manager.IsWifiEnabled)
{
_manager.StartScan();
}
...
}
And more extensive code from BroadcastReceiver:
public override void OnReceive(Context context, Intent intent)
{
MainActivity activity = (MainActivity)context.ApplicationContext;
activity._wifiSignals.Clear();
activity._wifiSignals.Add("Lista de wifi:\n");
IList<ScanResult> wifiScanList = activity._manager.ScanResults;
foreach (ScanResult wifiNetwork in wifiScanList)
{
activity._wifiSignals.Add(wifiNetwork.Ssid + ": " + wifiNetwork.Level);
}
//activity.presentation(activity._wifiSignals, activity);
activity._manager.StartScan();
}
Although I remember to call MainActivity properties from another activities in previous apps I developed, I'm pretty sure you cant call a function like you try to do with the StartScan().
The option I use normally is to store the data serialized, and call it in Main.
I do a class with some methods like:
class persistence
{
ISharedPreferences prefs;
ISharedPreferencesEditor editor;
public persistence(Context cont)
{
prefs = PreferenceManager.GetDefaultSharedPreferences(cont);
editor = prefs.Edit();
}
public void store(List<articulo> articulos)
{
string raw = JsonConvert.SerializeObject(articulos);
editor.PutString("articulos", raw);
editor.Commit();
}
public List<articulo> recover()
{
string raw = prefs.GetString("articulos", null);
List<articulo> lista;
if (raw == null)
lista = new List<articulo>();
else
lista = JsonConvert.DeserializeObject<List<articulo>>(raw);
return lista;
}
}
In your OnReceive function I call to the store function
In your OnCreate function you can do directly
persistence datos;
protected override void OnCreate(Bundle bundle)
{
_wifiReceiver = new wifiReceiver();
_manager = (WifiManager)GetSystemService(Context.WifiService);
datos = new persistence (this);
_wifiSignals = datos.recover();
if(_wifiSignals.Count>0)
StartScan();
}
This will also keep data from one usage to another, if you don't want just clear the persistence data after call the BroadcastReceiver;

nativeOnDraw failed - Xamarin Android Webview

Im using xamarin for android and i have looked into this issue but nothing seems to work.
Im trying to get a webview to work with a button but it keeps saying whenever i click on the button.
nativeOnDraw failed; clearing to background color.
I will include image of my layout and my code here.
MainActivity
namespace Application
{
[Activity(Label = "Application", MainLauncher = true, Icon = "#drawable/icon", Theme = "#android:style/Theme.NoTitleBar")]
public class MainActivity : Activity
{
protected override void OnCreate(Bundle bundle)
{
base.OnCreate(bundle);
// Set our view from the "main" layout resource
SetContentView(Resource.Layout.Main);
WebPage webPage = new WebPage();
Button btn_MySchedule = FindViewById<Button>(Resource.Id.btnSchedule);
Button btn_MyCareer = FindViewById<Button>(Resource.Id.btnCareer);
Button btn_MySocial = FindViewById<Button>(Resource.Id.btnSocial);
Button btn_Feedback = FindViewById<Button>(Resource.Id.btnFeedback);
Button btn_MyDetails = FindViewById<Button>(Resource.Id.btnDetails);
btn_MySchedule.Click += delegate
{
webPage.isSchedule = true;
//wPage.SetUrl("https://www.google.com");
StartActivity(typeof(WebPage));
};
}
}
}
WebPage
namespace Application
{
[Activity(Label = "WebPage", Theme = "#android:style/Theme.NoTitleBar")]
public class WebPage : Activity
{
public bool isSchedule;
private WebView _webView;
private string _url;
protected override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
SetContentView(Resource.Layout.WebPage);
_webView = FindViewById<WebView>(Resource.Id.webView);
new DisplayWebPage(_webView, GetUrl());
}
public string GetUrl()
{
return _url;
}
public void SetUrl(string sUrl)
{
_url = sUrl;
}
private void ButtonCLicked()
{
if (isSchedule == true)
{
SetUrl("https://www.google.com");
Toast.MakeText(this, "isSchedule is true", ToastLength.Short).Show();
}
}
}
}
I have found the issue. It was due to me calling an empty string via the GetUrl() methods.
The Solution I used is:
[Export("MyScheduleClicked")]
public void MyScheduleClicked(View v)
{
var activity2 = new Intent(this, typeof(WebPage));
activity2.PutExtra("MyURL", "https://www.google.com");
StartActivity(activity2);
}

Categories