ConnectivityManager connMgr = (ConnectivityManager)this.Activity.GetSystemService(Android.Content.Context.ConnectivityService);
NetworkInfo networkInfo = connMgr.ActiveNetworkInfo;
bool isConnected = networkInfo.IsConnected;
this code is in the onCreateView method in my fragment and when i run the app i get the error:
Unhandled Exception:
System.NullReferenceException: Object reference not set to an instance of an object. occurred
it would be great if someone would explain to me what "not set to an instance of an object means" as i dont quite understand. still a little new to xamarin and c# in general.
heres the fragament1.cs file:
using Android.OS;
using Android.Support.V4.App;
using Android.Views;
using Android.Webkit;
namespace TabsApp.Fragments
{
public class Fragment1 : Fragment
{
public override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
// Create your fragment here
}
public static Fragment1 NewInstance()
{
var frag1 = new Fragment1 { Arguments = new Bundle() };
return frag1;
}
WebView webView;
public override View OnCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
var ignored = base.OnCreateView(inflater, container, savedInstanceState);
View v = inflater.Inflate(Resource.Layout.fragment1, container, false);
webView = v.FindViewById<WebView>(Resource.Id.webView);
webView.LoadUrl("https://google.com");
webView.Settings.JavaScriptEnabled = true;
webView.SetWebViewClient(new WebViewClient());
return v;
}
public void OnBackPressed()
{
webView.GoBack();
}
}
}
and heres the MainActivity.cs file:
using Android.App;
using Android.OS;
using TabsApp.Fragments;
using Android.Content.PM;
using Android.Support.Design.Widget;
using Android.Support.V7.App;
namespace TabsApp
{
[Activity(Label = "#string/app_name", MainLauncher = true, LaunchMode = Android.Content.PM.LaunchMode.SingleTop, Icon = "#drawable/icon",
ConfigurationChanges = ConfigChanges.ScreenSize | ConfigChanges.Orientation, ScreenOrientation = ScreenOrientation.Portrait)]
public class MainActivity : AppCompatActivity
{
BottomNavigationView bottomNavigation;
protected override void OnCreate(Bundle bundle)
{
base.OnCreate(bundle);
SetContentView(Resource.Layout.main);
var toolbar = FindViewById<Android.Support.V7.Widget.Toolbar>(Resource.Id.toolbar);
if (toolbar != null)
{
SetSupportActionBar(toolbar);
SupportActionBar.SetDisplayHomeAsUpEnabled(false);
SupportActionBar.SetHomeButtonEnabled(false);
}
bottomNavigation = FindViewById<BottomNavigationView>(Resource.Id.bottom_navigation);
bottomNavigation.NavigationItemSelected += BottomNavigation_NavigationItemSelected;
LoadFragment(Resource.Id.menu_home);
}
private void BottomNavigation_NavigationItemSelected(object sender, BottomNavigationView.NavigationItemSelectedEventArgs e)
{
LoadFragment(e.Item.ItemId);
}
void LoadFragment(int id)
{
Android.Support.V4.App.Fragment fragment = null;
switch (id)
{
case Resource.Id.menu_home:
fragment = Fragment1.NewInstance();
break;
case Resource.Id.menu_audio:
fragment = Fragment2.NewInstance();
break;
case Resource.Id.menu_video:
fragment = Fragment3.NewInstance();
break;
}
if (fragment == null)
return;
SupportFragmentManager.BeginTransaction()
.Replace(Resource.Id.content_frame, fragment)
.Commit();
}
}
}
Well its pretty simple this looks to me like you do not have your activity context here and for that reason you are unable to get the connMgr
What you need to do is when you call your fragment from your activity pass the current activity to your ~Fragment~ something like this on your fragment call:
Fragment1 newInstance(this);
Receive it in your fragment with something like this in your constructor:
public static AppCompatActivity _activity
public static Fragment1 newInstance(AppCompatActivity activity )
{
_activity =activity ;
//Lines of code }
And in your onCreateView use it like this :
ConnectivityManager connMgr = (ConnectivityManager)_activity.GetSystemService(Android.Content.Context.ConnectivityService);
NetworkInfo networkInfo = connMgr.ActiveNetworkInfo;
bool isConnected = networkInfo.IsConnected;
If it doesn't work lemme know! Goodluck
Related
I am trying to create a tabbed Swipe navigation system in my xamarin android I am facing The name 'SupportFragmentManager' does not exist in the current context, error I have no idea how to clear this I am new to xamarin android please help me
MainActivity.cs
protected override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
SetContentView(Resource.Layout.GalleryPage);
// Create your application here
txtView = FindViewById<TextView>(Resource.Id.txtView);
_imageView = FindViewById<ImageView>(Resource.Id.imageView1);
Button button = FindViewById<Button>(Resource.Id.MyButton);
TabLayout tabLayout = (TabLayout)FindViewById(Resource.Id.tablayout_navigation);
ViewPager viewPager = (ViewPager)FindViewById(Resource.Id.pager);
SetupviewPager(viewPager);
tabLayout.SetupWithViewPager(viewPager);
button.Click += delegate
{
Intent = new Intent();
Intent.SetType("image/*");
Intent.SetAction(Intent.ActionGetContent);
StartActivityForResult(Intent.CreateChooser(Intent, "Select Picture"), PickImageId);
};
}
private void SetupviewPager(ViewPager viewPager)
{
viewPager.OffscreenPageLimit = 3;
var adapter = new PageAdapter1(SupportFragmentManager);
adapter.AddFragment(new Fragment1(), "Title1");
adapter.AddFragment(new Fragment2(), "Title2");
adapter.AddFragment(new Fragment3(), "Title3");
viewPager.Adapter = adapter;
}
PageAdapter1.cs
using System.Collections.Generic;
using Android.Support.V4.App;
using Java.Lang;
using Fragment = Android.Support.V4.App.Fragment;
using FragmentManager = Android.Support.V4.App.FragmentManager;
namespace OCR_Pro
{
public class PageAdapter1: FragmentPagerAdapter
{
private readonly List<Fragment> _fragments;
private readonly List<string> _fragmentnames;
public PageAdapter1(FragmentManager fm) : base(fm)
{
_fragments = new List<Fragment>();
_fragmentnames = new List<string>();
}
public override int Count
{
get { return _fragments.Count; }
}
public override Fragment GetItem(int position)
{
return _fragments[position];
}
public void AddFragment(Fragment fragment, string name)
{
if (fragment == null) return;
_fragments.Add(fragment);
_fragmentnames.Add(name);
}
public override ICharSequence GetPageTitleFormatted(int position)
{
return new Java.Lang.String(_fragmentnames[position]);
}
}
}
Fragment1.cs
using Android.OS;
using Android.Runtime;
using Android.Util;
using Android.Views;
using Android.Widget;
namespace OCR_Pro
{
public class Fragment1 : Android.Support.V4.App.Fragment
{
public override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
// Create your fragment here
}
public override View OnCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
// Use this to return your custom view for this Fragment
// return inflater.Inflate(Resource.Layout.YourFragment, container, false);
var v = inflater.Inflate(Resource.Layout.Fragment1, container, false);
return v;
}
}
}
Errror : The name 'SupportFragmentManager' does not exist in the current context
It looks like you are trying to pass in the class SupportFragmentManagerinstead of an instance of the class. Try instantiating an instance of SupportFragmentManager and then passing it in.
Please check if installing Xamarin.Android.Support.v4 by nuget package. SupportFragmentManager type is Android.Support.V4.App.FragmentManager.
If you want to get sample, please take a look:
https://learn.microsoft.com/en-us/xamarin/android/user-interface/controls/view-pager/viewpager-and-fragments
I'm trying to display only a small part of a webpage in Xamarin Android Webkit WebView. I've seen a lot of answers how to do this in android studio but I've not seen many recent answers for how to do it in xamarin for android. What method would you recommend for this task? I could also settle for loading a WebView and then scrolling down to a certain section of a page.
Here's the code I'm using to generate tab and WebView
//Discover new content
[Activity]
//define class discover content
public class SessionsActivity : Activity
{
protected override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
SetContentView(Resource.Layout.discover);
//declare webview and tell our code where to find the XAML resource
WebView discoverWebView = FindViewById<WebView>(Resource.Id.webViewDiscover);
//set the webview client
discoverWebView.SetWebViewClient(new WebViewClient());
//load the subscription url
discoverWebView.LoadUrl("https://www.bitchute.com/");
//enable javascript in our webview
discoverWebView.Settings.JavaScriptEnabled = true;
//zoom control on? This should perhaps be disabled for consistency?
//we will leave it on for now
discoverWebView.Settings.BuiltInZoomControls = true;
discoverWebView.Settings.SetSupportZoom(true);
//scrollbarsdisabled
// subWebView.ScrollBarStyle = ScrollbarStyles.OutsideOverlay;
discoverWebView.ScrollbarFadingEnabled = false;
}
}
thanks, in advance! =]
if you look at the Xamarin docs for WebView, you'll see that it has a LoadURL method with the same signature as the Java method. The only difference is the casing of the method - Xamarin usually uses C# casing, but otherwise the method names are the same, and the argument you pass will also be identical
discoverWebView.LoadUrl("javascript:(function() { " +
"document.getElementsByTagName('header'[0].style.display="none"; " +
"})()");
Here's how I did it, #Jason was helpful but a more complete answer is as follows, this loads duckduckgo.com then hides the content_homepage, scroll to mid-bottom:
using Android.Graphics.Drawables;
using Android.OS;
using Android.Support.V4.App;
using Android.Views;
using Android.Webkit;
using Android.Widget;
namespace BottomNavigationViewPager.Fragments
{
public class TheFragment1 : Fragment
{
string _title;
string _icon;
protected static WebView _wv;
public static TheFragment1 NewInstance(string title, string icon) {
var fragment = new TheFragment1();
fragment.Arguments = new Bundle();
fragment.Arguments.PutString("title", title);
fragment.Arguments.PutString("icon", icon);
return fragment;
}
public override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
if (Arguments != null)
{
if(Arguments.ContainsKey("title"))
_title = (string)Arguments.Get("title");
if (Arguments.ContainsKey("icon"))
_icon = (string)Arguments.Get("icon");
}
}
public override View OnCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
var view = inflater.Inflate(Resource.Layout.TheFragmentLayout1, container, false);
_wv = view.FindViewById<WebView>(Resource.Id.webView1);
var _wvc = new MyWebViewClient();
_wv.SetWebViewClient(_wvc);
//string _wtf = "header";
_wv.Settings.JavaScriptEnabled = true;
_wv.Settings.AllowFileAccess = true;
_wv.Settings.AllowContentAccess = true;
//_wvc.OnPageFinished(_wv, _jsHideBannerC);
_wv.LoadUrl("https://www.duckduckgo.com/");
return view;
}
private class MyWebViewClient : WebViewClient
{
public override void OnPageStarted(WebView view, string url, Android.Graphics.Bitmap favicon)
{
base.OnPageStarted(view, url, favicon);
}
public override void OnPageFinished(WebView view, string url)
{
base.OnPageFinished(view, url);
string _jsHideBanner = "javascript:(function() { " +
"document.getElementById('content_homepage').style.display='none'; " + "})()";
string _jsHideBannerC = "javascript:(function() { " +
"document.getElementsByClassName('logo-wrap--home').style.display='none'; " + "})()";
_wv.LoadUrl(_jsHideBanner);
}
}
}
}
There was a problem parsing the package while installing .apk file.
Given below is configuration and code.
VS2015
MainActivity.cs
namespace WebAp
{
[Activity(Label = "TC", MainLauncher = true, Theme ="#android:style/Theme.NoTitleBar")]
public class MainActivity : Activity
{
private WebView web_view;
protected override void OnCreate(Bundle bundle)
{
base.OnCreate(bundle);
// Set our view from the "main" layout resource
SetContentView(Resource.Layout.Main);
web_view = FindViewById<WebView>(Resource.Id.webview);
web_view.Settings.JavaScriptEnabled = true;
web_view.LoadUrl("http://www.tc.com");
web_view.SetWebViewClient(new HelloWebViewClient());
}
public class HelloWebViewClient : WebViewClient
{
public override bool ShouldOverrideUrlLoading(WebView view, string url)
{
view.LoadUrl(url);
return true;
}
}
public override bool OnKeyDown(Android.Views.Keycode keyCode, Android.Views.KeyEvent e)
{
if (keyCode == Android.Views.Keycode.Back && web_view.CanGoBack())
{
web_view.GoBack();
return true;
}
return base.OnKeyDown(keyCode, e);
}
}
}
Configurataion :
enter image description here
Thats it my code. I was also try different API for Compile, Min and target version.
Please help me thanks.
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);
}
I'm starting my first Xamarin.Forms app in Visual Studio 2015 on Windows.
My StartUp project is firstApp.Droid.
In MainActivity.cs in firstApp.Droid I have this code:
namespace firstApp.Droid
{
[Activity (Label = "firstApp", Icon = "#drawable/icon", MainLauncher = true, ConfigurationChanges = ConfigChanges.ScreenSize | ConfigChanges.Orientation)]
public class MainActivity : global::Xamarin.Forms.Platform.Android.FormsApplicationActivity
{
protected override void OnCreate (Bundle bundle)
{
base.OnCreate (bundle);
global::Xamarin.Forms.Forms.Init (this, bundle);
LoadApplication (new firstApp.App ());
}
}
}
In App.cs I have this code:
public App ()
{
// The root page of your application
MainPage = new NavigationPage(new SensorPage());
}
And in SensorPage.cs I have this auto-generated code:
public class SensorPage : ContentPage
{
public SensorPage ()
{
Content = new StackLayout {
Children = {
new Label { Text = "Hello SensorPage" } //line that causes the error
}
};
}
}
When I try to compile the app, I get the error:
CS0104 'Label' is an ambiguous reference between 'Xamarin.Forms.Label' and 'System.Reflection.Emit.Label'
What should I do to resolve this?
either remove using System.Reflection.Emit; from the top of your SensorPage.cs, or alternately use an explicit namespace for Label:
Content = new StackLayout {
Children = {
new Xamarin.Forms.Label { Text = "Hello SensorPage" }
}
};