Xamarin Android [Application] annotation and static values

276 views Asked by At

I have a simple Android application that needs to save an authentication session object to communicate with a REST API when the app runs.

My impression was to make this session object available as a static object as part of my Android Application class and to initialise the session within this context:

[Application]
public class MyApp : Application
{
    static public Session session;

    public MyApp(IntPtr handle, JniHandleOwnership transfer) : base(handle,transfer)
    {
        // database is initialised here

        MyApp.session = new Session (database);
    }
}

This seems to work well until I discovered that when I tried to access the MyApp.session from within my MainActivity that MyApp.session was set to null.

I'm now using the MainActivity class OnCreate method to initialise the session and now the session seems to keep it value.

Is there something with the Application class and static variables I'm not aware off? I was assuming that the instance of MyApp would be available throughout the lifetime of the application.

Can I still use the Application class to initialise variables or is this best done in the OnCreate of the MainActivity?

0

There are 0 answers