'May be the Application not created?

I have some Apps where I use a static reference of the Application instance. That's usefull when I need to use context in some singleton Class that has application lifetime. Here an example:

public class MyApp  extends Application
{
    private static MyApp smApplication;    

    public MyApp()
    {
        MyApp.smApplication = this;
    }

    public void onCreate()
    {
        super.onCreate();

        MyApp.smApplication = this;
    }

    public static MyApp getApp() {
        return MyApp.smApplication;
    }
}

class Settings  // Example of Singleton class
{
    ...  

    public boolean loadSettings()
    {
        Context context = MyApp.getApp();  // NullPointerException on the next line
        SharedPreferences pref = context.getSharedPreferences(SHAREDPREF_FILENAME, Context.MODE_PRIVATE);

        ...
    }
}

This works like a charm in the majority of the cases. But... I have a number of NullPointerException crashes reported in the Play Console about that Context. Usually called in the MainActivity.onCreate or MyService.onCreate. Application should Always be created before any other Activiy or Service. So I can't understand what happens. I've never had a similar crash on any of my devices.

smApplication is initialized in the constructor and never set to null. It seems that in that cases Application is not created. It's also weird that all these crashes are reported in the PlayConsole but I cannot find them in Firebase Crashlitics as if neither Crashlitics has yet initialized in that cases (and FC shoul be initialized by the Application)

This has been happening for years in a small part of my users.

Any suggestion?

PS. I Do not need suggestion on code refactoring, just to understand what happens and how to avoid it.



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source