I have searched for issues similar to the one I'm experiencing to no avail, so I apologize if this question has been answered elsewhere. I found many that seemed adjacent, but none of the answers I've found thus far have helped in my particular context.
I'm developing a Xamarin.Android app that makes use of the Application instance to store some global variables. Here is my Application class:
[Register("android/app/Application", DoNotGenerateAcw = true)]
public class MainApplication : Application
{
public VariablesModel Variables { get; set; }
public MainApplication(IntPtr javaReference, JniHandleOwnership transfer) : base(javaReference, transfer)
{
Variables = new VariablesModel();
}
}
I am normally able to access this Application instance from inside of an Activity (or Activity context) by doing the following:
var application = (MainApplication)Application.Context;
var variables = application.Variables;
It is a new development that the first line of the two above throws a System.InvalidCastException
when trying to cast to MainApplication
. What is especially confounding to me is that we have shipped versions of this app that are using the code above successfully. It is only now in my development environment that I am unable to get it working, even when I pull those previous working versions.
The only thing that I can think is that an Android SDK update has prompted this difference in behavior, but I have yet to find any documentation (or see any useful Exceptions other than the InvalidCast) that help to clarify what I'm missing. MainApplication is inheriting Application
, and though Application.Context
is listed as a Context
type, again, this cast has worked for me in the past.
Is there something I'm missing? What do I need to do in order to get access to the running Application instance?