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());
}
}
}
DependencyServicebefore callingXamarin.Forms.Forms.Init(this, bundle);(sinceInitgets all of the Xamarin Forms classes available for use). Also, if you are already in yourMainActivity, why not just run the following:new HPost_droid().HPost("R");? You do not needDependencyServicewhen you are already in your native project. Maybe tell us what you are trying to accomplish withHPost()- hvaughan3