I use some singletons in my Android app. From my GlobalApp (extends Application) class in onCreate() they are initialized like this:
public class GlobalApp extends Application{
@Override
public void onCreate() {
super.onCreate();
DatabaseHelper databaseHelper = new DatabaseHelper(getApplicationContext());
MySingleton.init(databaseHelper);
}
}
And the singleton:
public class MySingleton{
static MySingleton instance;
DatabaseHelper databaseHelper;
public static void init(DatabaseHelper databaseHelper){
instance = new MySingleton(databaseHelper);
}
}
I receive crashes for my app which clearly show that instance is null sometimes while my app runs. Most weird thing: those crashes only happen on the Samsung Galaxy S5!
My understanding was that
the
onCreate()method of myapplicationclass was guaranteed to be called when my app is startedthe instance on a Singleton could never become null, except for when the app would be completely restarted (in which case it should by recreated by my
applicationclass).
What's going on here?
PS: I know that Singletons are kinda frowned upon and extending the application class is also not recommended by everyone, but that's not the point here.
EDIT: Just for clarification, the code works 99% of the time. The question is not asking on how to implement the singleton pattern but rather how the lifecycle of my (or any) app can lead to the instance of a Singleton becoming null when it is created in the application's onCreate().
You should have a constructor that accepts DatabaseHelper objects also make instance as static...