I'd like to put my database connection object to Application class. I read some tutorials and everywhere I see explicit implementation of a singleton pattern. Something like this
public class MyApplication extends Application {
private static MyApplication singleton;
public static MyApplication getInstance(){
return singleton;
}
@Override
public void onCreate() {
super.onCreate();
singleton = this;
}
}
My question is why do I need to do this explicit implementation? Nobody explains.
I'd like to add there some property, initialized in onCreate()
and get it's value in activity.
myProp = (MyApplication)getApplicationContext().getMyProperty()
Is it really necessary to implement singleton pattern?
An
Application
class is an access point to application context and generally it is used as a initializator for all application-scoped dependencies like your database object. This class is initialized only once per application and persists in memory until application is no longer in memory. So it is a natively created singleton.By having such static access point to application you may have access to the application context in any class and in general case this context is much better for retrieving resources, system services etc. when you need such dependencies in your custom classes, because it doesn't hold a link to the activity and view so is a leak-safe. Of course in your example the
Activity
has an access to application, but you have to cast context anyway and better use same approach for a whole app.Despite you may use it like a global access point to all application scoped and initialized dependencies, do not overload it with huge initialization logic, better create some other singletons for this purpose and just initialize it from
Application
class. In a big project consider using DI framework, Dagger the best one, for providing dependencies.