Skip to content
This repository has been archived by the owner on Aug 22, 2019. It is now read-only.

Inject Contexts in Fields without cluttering your onCreate !

License

Notifications You must be signed in to change notification settings

thomhurst/android-contextinjector

Repository files navigation

Android Context Injector

Inject Contexts in Fields without cluttering your onCreate !

Install

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}'

Usage

Your Context can be used in Fields/Properties and so your onCreate method doesn't have to be cluttered!

Context

val myField by ContextInjector(this) { context -> ... /* Use context from lambda */ }

Example

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
    }

}

Activity

val myField by ActivityInjector(this) { activity -> ... /* Use activity from lambda */ }

Example

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
    }

}

About

Inject Contexts in Fields without cluttering your onCreate !

Resources

License

Stars

Watchers

Forks

Packages

No packages published