Skip to content

Instantly share code, notes, and snippets.

@donrokzon
Created March 7, 2019 05:33
Show Gist options
  • Select an option

  • Save donrokzon/130b830d1be27e12446358a9c3c7c4e3 to your computer and use it in GitHub Desktop.

Select an option

Save donrokzon/130b830d1be27e12446358a9c3c7c4e3 to your computer and use it in GitHub Desktop.
Dependency injection
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