Exception: System.NullReferenceException Message=The current Activity can not be detected. Ensure that you have called Init in your Activity or Application class.
Where I’m getting this issue: While hitting the API using httpclient as below
var content = new StringContent(jsonData, Encoding.UTF8, "application/json");
var response = await _client.PostAsync(uri, content);
Please help me with your suggestions
Environment: .NET 8, Android, MAUI, Visual studio.
Situation: I upgraded the Android Xamarin (.NET Framework) application to MAUI.
MainActivity Class:
[Activity(Name = "Test.MainActivity", Label = "Test Mobile", Icon = "@drawable/icon"
, LaunchMode = LaunchMode.SingleTask, MainLauncher = true, ScreenOrientation = ScreenOrientation.Portrait, Theme = "@style/Maui.SplashTheme"
, ConfigurationChanges = ConfigChanges.ScreenSize | ConfigChanges.Orientation)]
public class MainActivity : global::Microsoft.Maui.MauiAppCompatActivity
{
internal static MainActivity Instance { get; private set; }
// for FCM push notifications
internal static readonly string CHANNEL_ID = "fcm_notification_channel";
internal static readonly int NOTIFICATION_ID = 100;
enum EnvCheckType { Root, Debug, Emulator, Hooks, CustomFirmware, IntegrityCheck, WirelessSecurity };
static BitArray envChecks = new BitArray(7);
private MyBroadcastReceiver mMessageReceiver = new MyBroadcastReceiver();
protected override void OnCreate(Bundle savedInstanceState)
{
try
{
Instance = this;
base.OnCreate(savedInstanceState);
}
catch (Exception ex)
{
ExceptionLogger.LogErrorAsync(ex);
}
}
}
MainApplication:
[Application]
public class MainApplication : MauiApplication
{
// for FCM push notifications
internal static readonly string CHANNEL_ID = "fcm_notification_channel";
internal static readonly int NOTIFICATION_ID = 100;
enum EnvCheckType { Root, Debug, Emulator, Hooks, CustomFirmware, IntegrityCheck, WirelessSecurity };
static BitArray envChecks = new BitArray(7);
public MainApplication(nint handle, JniHandleOwnership ownership) : base(handle, ownership)
{
}
protected override MauiApp CreateMauiApp()
{
var builder = MauiApp.CreateBuilder();
builder.UseMauiApp<App>().UseMauiCommunityToolkit();
return builder.Build();
}
}
I tried making multiple changes regarding the Mainactivity and HttpClient but nothing worked