Search code examples
androidxamarin.formsauth0

Xamarin StartActivity ActionView - NullPointerException Attempt invoke virtual method


I am trying to create a Xamarin Forms app that uses the Auth0 services for login. I have been following their instructions on how to make it work but it seems to crash each time.

The uri is created and is valid so the implementation of the client seems fine but when the line StartActivity is called I get this error :

Attempt to invoke virtual method 'android.app.ActivityThread$ApplicationThread android.app.ActivityThread.getApplicationThread()' on a null object reference

I thinks it is linked with the fact that I use a DependencyService to be able to call the function in the Android and iOS project and it runs in Async but I can't find anything else to do to make it work.

I tried to use RunOnUiThread and BeginInvokeOnMainThread but the result is stillthe same.

I have followed theses instructions and examples:

Auth0 Instructions

Github Example

So I created a simple View with a button to tap to login using their service. This button call a delegate service to be able to launch the instructions in Android and iOS

XAML Code for the Login button

<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
         xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
         x:Class="App.LoginPage">
<ContentPage.Content>
    <StackLayout VerticalOptions="StartAndExpand">
        <Button x:Name="LoginButton" Text="Login / Signup" Clicked="OnLoginSignupButtonClicked" />
    </StackLayout>
</ContentPage.Content>

Button Code that call the dependencyservice

void OnLoginSignupButtonClicked(object sender, EventArgs e)
{
    DependencyService.Get<ILoginButton>().LoginRegisterButtonTap();
}

Then I execute the code they provide in the implementation of the method

public async void LoginRegisterButtonTap()
{
    // Prepare for the login
    try
    {
        authorizeState = await client.PrepareLoginAsync();
        // Send the user off to the authorization endpoint
        var uri = Android.Net.Uri.Parse(authorizeState.StartUrl);
        var intent = new Intent(Intent.ActionView, uri);
        intent.AddFlags(ActivityFlags.NoHistory);
        StartActivity(intent);
    } catch (Exception e)
    {
        Console.WriteLine(e.Message);
    }
 }

Solution

  • TLDR The issue was happening because I needed to specify the application context from the MainActivity and now everything works.

    Application.Context.StartActivity(intent);
    

    I spend many hours looking into that issue and the solution was on a simple tutorial about how to create new intent in Xamarin from the Android project and it worked.