Created
March 7, 2019 05:33
-
-
Save donrokzon/130b830d1be27e12446358a9c3c7c4e3 to your computer and use it in GitHub Desktop.
Dependency injection
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| public class BaseActivity extends AppCompatActivity { | |
| @Inject SharedPreferences prefs; | |
| @Override | |
| protected void onCreate(@Nullable Bundle savedInstanceState) { | |
| super.onCreate(savedInstanceState); | |
| ((DaggerApplication)getApplication()).getAppComponent().inject(this); | |
| } | |
| } | |
| ................... | |
| @Singleton @Component(modules = AppModule.class) | |
| public interface AppComponent { | |
| void inject(DaggerApplication daggerApplication); | |
| void inject(BaseActivity baseActivity); | |
| } | |
| ................... | |
| @Module public class AppModule { | |
| private final DaggerApplication application; | |
| public AppModule(DaggerApplication application) { | |
| this.application = application; | |
| } | |
| @Provides @Singleton | |
| Context providesApplicationContext(){ | |
| return application; | |
| } | |
| @Provides @Singleton | |
| SharedPreferences providesSharedPreferences(Context context){ | |
| return context.getSharedPreferences("My_Prefs_Title",Context.MODE_PRIVATE); | |
| } | |
| } | |
| ................... | |
| public class DaggerApplication extends Application { | |
| private AppComponent appComponent; | |
| @Override | |
| public void onCreate() { | |
| super.onCreate(); | |
| appComponent=DaggerAppComponent.builder().appModule(new AppModule(this)).build(); | |
| appComponent.inject(this); | |
| } | |
| public AppComponent getAppComponent() { | |
| return appComponent; | |
| } | |
| } | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment