TobiasBuchholz / Plugin.Firebase

Wrapper around the native Android and iOS Firebase Xamarin SDKs
MIT License
220 stars 49 forks source link

System.NullReferenceException Current Activity is null when implementing Firebase Authentication #124

Closed Govern24 closed 1 year ago

Govern24 commented 1 year ago

Current Activity is null, ensure that the MainApplication.cs file is setting the CurrentActivity in your source code so Firebase Analytics can use it.

   private static MauiAppBuilder RegisterFirebaseServices(this MauiAppBuilder builder)
    {

        `builder.ConfigureLifecycleEvents(events =>
        {
#if IOS
            events.AddiOS(iOS => iOS.FinishedLaunching((app, launchOptions) => {
                CrossFirebase.Initialize(app, launchOptions, CreateCrossFirebaseSettings());
                return false;
            }));
#else
            events.AddAndroid(android => android.OnCreate((activity, state) =>
                CrossFirebase.Initialize(activity, state, CreateCrossFirebaseSettings())));
#endif
        });

        builder.Services.AddSingleton(_ => CrossFirebaseAuth.Current); //Exception is thrown on this line

        return builder;
    }

This is how my MainActivity looks like:

[Activity(Theme = "@style/Maui.SplashTheme", MainLauncher = true, ConfigurationChanges = ConfigChanges.ScreenSize | ConfigChanges.Orientation | ConfigChanges.UiMode | ConfigChanges.ScreenLayout | ConfigChanges.SmallestScreenSize | ConfigChanges.Density)]
public class MainActivity : MauiAppCompatActivity
{
    protected override void OnCreate(Bundle savedInstanceState)
    {
        base.OnCreate(savedInstanceState);
    }

    protected override void OnActivityResult(int requestCode, Result resultCode, Intent data)
    {
        base.OnActivityResult(requestCode, resultCode, data);
        FirebaseAuthImplementation.HandleActivityResultAsync(requestCode, resultCode, data);

    }
}

This is the MainApplication class:

[Application]
public class MainApplication : MauiApplication
{
    public MainApplication(IntPtr handle, JniHandleOwnership ownership)
        : base(handle, ownership)
    {
    }

    protected override MauiApp CreateMauiApp() => MauiProgram.CreateMauiApp();
}
TobiasBuchholz commented 1 year ago

Hmm, I can't see any problem with your code so far. The android FirebaseAuthImplementation class uses the Microsoft.Maui.ApplicationModel.Platform.CurrentActivity object and this seems to be null for some reason, so maybe your Maui setup is wrongly configured somehow? Are you calling .UseMauiApp<App>() on the MauiAppBuilder in your MauiProgramm file?

TobiasBuchholz commented 1 year ago

Furthermore I've released a new version 1.3.0 which might fix the problem, see https://github.com/TobiasBuchholz/Plugin.Firebase/issues/67#issuecomment-1409304552