Skip to content

Instantly share code, notes, and snippets.

@otoo-peacemaker
Last active December 19, 2022 11:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save otoo-peacemaker/a5434461693358642198084a2b519804 to your computer and use it in GitHub Desktop.
Save otoo-peacemaker/a5434461693358642198084a2b519804 to your computer and use it in GitHub Desktop.
How to get application context everywhere in your android application using manual Dependency Injection.
<Application
..........
android:name=".MyApplication"
............
/**
* Container of objects shared across the whole app.
* To solve the issue of reusing objects, you can create your own dependencies container class that you use to get dependencies.
* All instances provided by this container can be public. In the example, because you only need an instance of UserPreferences,
* you can make its dependencies private with the option of making them public in the future if they need to be provided:
* */
class AppContainer {
//getting the UserPreference everywhere in our app.
val preference by lazy { UserPreference(MyApplication.instance) }
}
//You use it anywhere in your without the need of creating the application context anytime you want it.
val contex:Context = MyApplication.instance
/**
* [MyApplication] is the Base class for maintaining global application state.
* Specify fully-qualified name of this subclass as the "android:name" attribute in [AndroidManifest.xml's] <application> tag.
* This subclass of the Application class, is instantiated before any other class when the process for your application/package is created.
*Note: Getting application context in singletons/static fields, this leads to memory leaks (and also breaks Instant Run).
* Why because a static variable is a variable that has been allocated "statically", meaning that its lifetime (or "extent") is the entire run of the program.
* so this keeps copies of data or values in memory and also exposes app resources.
*
* The [instance] variable to provide the application context of this application without the need of always creating and instantiating context anytime we need it.
* It allows access to application-specific resources and classes
*
* The [appContainer] variable get the the [AppContainer] instance
* */
class MyApplication: Application() {
companion object {
//use this to get the context of this application
lateinit var instance: MyApplication
private set
//getting the UserPreference everywhere in our app.
val preference = UserPreference(instance)
}
override fun onCreate() {
super.onCreate()
instance = this
}
// Instance of AppContainer that will be used by all the Activities of the app
//get the container like this in the activity/fragment class val appContainer = (application as Sim2Application).appContainer
val appContainer = AppContainer()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment