Add Jitpack to your repositories in your build.gradle
file
allprojects {
repositories {
// ...
maven { url 'https://jitpack.io' }
}
}
Add the below to your dependencies, again in your gradle.build
file
implementation 'com.github.thomhurst:android-contextinjector:{version}'
Your Context can be used in Fields/Properties and so your onCreate method doesn't have to be cluttered!
val myField by ContextInjector(this) { context -> ... /* Use context from lambda */ }
class MyActivity : Activity() {
// WILL CRASH
val unSafeSharedPreferences = PreferenceManager.getDefaultSharedPreferences(this)
// Will not crash
val safeSharedPreferences by ContextInjector(this) { context -> PreferenceManager.getDefaultSharedPreferences(context) }
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
val someSavedVariable = safeSharedPreferences.getString("key", null)
// Etc
}
}
val myField by ActivityInjector(this) { activity -> ... /* Use activity from lambda */ }
class MyActivity : Activity() {
// WILL CRASH
val unSafeAlert = AlertDialog.Builder(this)
.setTitle("Some Title")
.setMessage("Some Message")
// Will not crash
val safeAlert by ActivityInjector(this) { activity ->
AlertDialog.Builder(activity)
.setTitle("Some Title")
.setMessage("Some Message")
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
safeAlert.show()
// Etc
}
}