C#C
C#3y ago
3 replies
uselessxp

❔ Xamarin.Forms Android App problem using Application.Context.StartActivity(intent)

Hi, in short, I created a super small Xamarin.Forms Android App.
All I need is just to press a button, that will launch another application.

Then I immedaitely added the button in the myPage.xaml file in the shared Xamarin.Forms project.
About the myPage.xaml.cs file this is the code I binded to the button:
private void OnMyButtonClicked(object sender, EventArgs e)
{
  DependencyService.Get<IAppLauncher>().LaunchApp("com.android.chrome", "test");
}


I defined the interface into App.xaml.cs (still shared project) using
public interface IAppLauncher
{
    void LaunchApp(string packageName, string data);
}


Then I implmented it in the Android project by adding some code into MainActivity.cs
namespace AppExample1.Droid
{
    public class AppLauncherImplementation : IAppLauncher
    {
        public void LaunchApp(string packageName, string data)
        {
            var uri = Android.Net.Uri.Parse($"appexample2://data/{data}");
            var intent = new Intent(Intent.ActionView, uri);
            intent.SetPackage(packageName);

            var context = Android.App.Application.Context;
            context.StartActivity(intent);
        }
    }
}


The problem is that every time I click the button, for some reason that I don't know, I always get error
System.NullReferenceException: 'Object reference not set to an instance of an object.'
Was this page helpful?