androidxamarinmaui.net-maui

Java.Lang.NullPointerException: 'Attempt to invoke virtual method 'void android.app.Activity.requestPermissions(java.lang.String[], int)'


I have tried to request on App's class to request the READ_CONTACTS permissions but throws an exception Exception Java.Lang.NullPointerException: 'Attempt to invoke virtual method 'void android.app.Activity.requestPermissions(java.lang.String[], int)' on a null object reference'

{
    public App(SignalrMessenger signalrMessenger, ChatServicesSettings chatServicesSettings, ContactServices contactServices)
    {
        InitializeComponent();
        

        if (!IsPermissioGranted(Android.App.Application.Context, Manifest.Permission.ReadContacts))
        {
            RequestPermission(Android.App.Application.Context as Activity, new[] { Manifest.Permission.ReadContacts }).GetAwaiter().GetResult();
        }

        MauiApplicationServices.WasDatabaseUpdatedOnStartUp = contactServices.SynchronizeDbWithLocalContacts().GetAwaiter().GetResult();

        MainPage = new MainPage(signalrMessenger,chatServicesSettings);//new AppShell();
    }
    public bool IsPermissioGranted(Context ctx, string permission)
    {
        return ActivityCompat.CheckSelfPermission(ctx, permission)== Permission.Granted;
    }
    public async Task RequestPermission(Activity activity, params string[] permissions)
    {
        ActivityCompat.RequestPermissions(activity, permissions, 0);
        await Task.CompletedTask;
    }
}

So I wonder if there is possibly a way to ask for permission in an Activity and inject a service OnCreate method? since the default ctor is called in the MainActity app initialization


Solution

  • OnCreate method will be triggered as expected in MainActivity class.

    You can ask for the permission inside MainActivity instead of App class.

    Sample code

    protected override void OnCreate(Bundle savedInstanceState)
        {
            base.OnCreate(savedInstanceState);
    
            if (ContextCompat.CheckSelfPermission(this, Manifest.Permission.Camera) == (int)Permission.Granted)
            {
                // We have permission, go ahead and use the camera.
            }
            else
            {
                ActivityCompat.RequestPermissions(this, new String[] { Manifest.Permission.Camera },0);
            }
        }
    
    public override void OnRequestPermissionsResult(int requestCode, string[] permissions, Permission[] grantResults)
        {
             base.OnRequestPermissionsResult(requestCode, permissions, grantResults);
        }