I want to use a variabele or method from my MainPage in my MainActivity. I have created an interface for my DependencyService but I always have the same error at
DependencyService.Get<IHPost>.HPost("R");
Method not valid in the given context
I followed the official documentation,so I created my interface in the PCL:
IHPost (public interface)
In Xamarin.Android i have written the implementation HPost_droid with
[assembly: Dependency(typeof(HPost_droid))] line
and in MainActivity i added this interface.
Code :
IHPost.cs (Interface)
namespace Xam
{
public interface IHPost
{
void HPost(string val);
}
}
MainPage.xaml.cs
public partial class MainPage : ContentPage
{
public MainPage()
{
InitializeComponent();
// DependencyService.Get<IHPost>.HPost("R");
}
}
HPost_droid (Class)
[assembly: Dependency(typeof(HPost_droid))]
namespace Xam.Droid
{
class HPost_droid : Java.Lang.Object, IHPost
{
public HPost_droid() { }
public void HPost(string val)
{
System.Diagnostics.Debug.Write(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>" + val);
}
}
}
MainActivity
[assembly: Xamarin.Forms.Dependency(typeof(IHPost))]
namespace Xam.Droid
{
[Activity(Label = "Xam", Icon = "#drawable/icon", Theme = "#style/MainTheme", MainLauncher = true, ConfigurationChanges = ConfigChanges.ScreenSize | ConfigChanges.Orientation)]
public class MainActivity : Xamarin.Forms.Platform.Android.FormsAppCompatActivity, IHPost
{
protected override void OnCreate(Bundle bundle)
{
TabLayoutResource = Resource.Layout.Tabbar;
ToolbarResource = Resource.Layout.Toolbar;
DependencyService.Get<IHPost>.HPost("R");
base.OnCreate(bundle);
global::Xamarin.Forms.Forms.Init(this, bundle);
LoadApplication(new App());
}
}
}
I retry from scratch application following this perfect tutorial : https://wolfprogrammer.com/2016/08/05/dependency-services-with-xamarin-forms/
and it's work !
Related
I wrote a code in a class to notify me using the notificationCompat.Builder and it's giving me this error, It's telling me that I've done something before OnCreate(), Inside MainActivity I'm declaring another class in order to Inherit CountDownTimer class and inside the OnFinished () method I wrote this small code and it's giving me an Error. Can anyone help me ? I believe using this.activity is causing the problem but I don't know a workaround for this :
public NotificationCompat.Builder builder;
MainActivity activity = new MainActivity();
NotificationManagerCompat notificationManager;
public override void OnFinish()
{
Toast.MakeText(Application.Context ,"Finished",ToastLength.Short).Show();
builder = new NotificationCompat.Builder(this.activity, CHANNEL_ID).SetAutoCancel(true)
.SetContentTitle("CountDownTimer !!")
.SetSmallIcon(Resource.Drawable.abc_ic_star_black_48dp)
.SetContentText($" Stopped"); // display.
notificationManager = NotificationManagerCompat.From(this.activity); Error // Java.Lang.IllegalStateException: 'System services not available to Activities...
notificationManager.Notify(NOTIFICATION_ID, builder.Build());
}
This is code is just to illustrate Reference to current Activity :
[Activity(Label = "#string/app_name", Theme = "#style/AppTheme", MainLauncher = true)]
public class MainActivity : AppCompatActivity
{
static Context context;
protected override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
Xamarin.Essentials.Platform.Init(this, savedInstanceState);
// Set our view from the "main" layout resource
SetContentView(Resource.Layout.activity_main);
context = this;
}
public class CountDown1 : CountDownTimer
{
public NotificationCompat.Builder builder;
NotificationManagerCompat notificationManager;
public override void OnFinish()
{
Toast.MakeText(Application.Context ,"Finished",ToastLength.Short).Show();
builder = new NotificationCompat.Builder(context, CHANNEL_ID).SetAutoCancel(true)
.SetContentTitle("CountDownTimer !!")
.SetSmallIcon(Resource.Drawable.abc_ic_star_black_48dp)
.SetContentText($" Stopped"); // the message to display.
notificationManager = NotificationManagerCompat.From(context);// Java.Lang.IllegalStateException: 'System services not available to Activities before onCreate()'
notificationManager.Notify(NOTIFICATION_ID, builder.Build());
}
}
}
}
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
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.
I wanna point out that i'm a total newbie in Xamarin.
My goal is to create simple app that after you push the button, it will jump to another layout. My problem is, that after i created a new layout(called layout1) and new activity, I can't reference to this layout in my MainActivity.
freshly created Activity:
namespace Layouts
{
[Activity(Label = "Activity1")]
public class Activity1 : Activity
{
protected override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
SetContentView(Resource.Layout.layout1);
}
}
}
And my MainActivity:
namespace Layouts
{
[Activity(Label = "Layouts", MainLauncher = true, Icon = "#drawable/icon")]
public class MainActivity : Activity
{
protected override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
SetContentView (Resource.Layout.Main);
Button button1 = FindViewById<Button>(Resource.Id.button);
button1.Click += delegate
{
StartActivity(typeof(layout1)); //can't reference layout1 there
};
}
}
}
Any help will be great, thanks :)
StartActivity(typeof(Activity1));
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" }
}
};