Android Tutorial
Software Setup and Configuration
Android Studio
File Structure
Components
Core Topics
Layout
View
Button
Intent and Intent Filters
Toast
RecyclerView
Fragments
Adapters
Other UI Component
Image Loading Libraries
Date and Time
Material Design
Bars
Working with Google Maps
Chart
Animation
Database
Advance Android
Jetpack
Architecture
App Publish
App Monetization
Dependency Injection (DI) is a technique where one object supplies the dependencies of another object rather than having them hard-coded. Dagger 2 is one of the most popular dependency injection libraries in Android, and it generates code to handle the injection, ensuring that the process is efficient and optimized.
Here's a step-by-step guide on how to use Dagger 2 in an Android project:
Firstly, you need to add the Dagger 2 dependencies in your app's build.gradle
file:
implementation 'com.google.dagger:dagger:2.x' kapt 'com.google.dagger:dagger-compiler:2.x'
For Android, you'll also need:
implementation 'com.google.dagger:dagger-android:2.x' implementation 'com.google.dagger:dagger-android-support:2.x' // if you use support libraries kapt 'com.google.dagger:dagger-android-processor:2.x'
Don't forget to apply the Kotlin annotation processor plugin at the top:
apply plugin: 'kotlin-kapt'
Components are interfaces through which Dagger knows which modules to use and where to inject the dependencies:
@Component(modules = [AppModule::class]) interface AppComponent { fun inject(application: MyApplication) }
Modules are classes filled with methods that provide dependencies:
@Module class AppModule(private val application: MyApplication) { @Provides fun provideContext(): Context = application }
class MyApplication : Application() { lateinit var appComponent: AppComponent override fun onCreate() { super.onCreate() appComponent = DaggerAppComponent.builder() .appModule(AppModule(this)) .build() appComponent.inject(this) } }
Note: DaggerAppComponent
is generated by Dagger. If it doesn't appear initially, try building your project.
Now that everything is set up, you can inject dependencies into your classes. For example, in an Activity:
class MainActivity : AppCompatActivity() { @Inject lateinit var someClass: SomeClass override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) (application as MyApplication).appComponent.inject(this) // Now you can use `someClass` } }
Ensure that your AppComponent
knows where to inject:
@Component(modules = [AppModule::class]) interface AppComponent { fun inject(application: MyApplication) fun inject(activity: MainActivity) }
Dagger Android simplifies the process by reducing boilerplate code. With Dagger Android, you typically don't need to call the inject
method manually.
Instead of initializing Dagger in the Application
class, you can extend DaggerApplication
:
class MyApplication : DaggerApplication() { override fun applicationInjector(): AndroidInjector<out DaggerApplication> { return DaggerAppComponent.builder().create(this) } }
In Activities
, instead of AppCompatActivity
, you'd extend DaggerAppCompatActivity
.
This guide provides a basic understanding of Dagger 2 setup in Android. Dagger 2 has a steep learning curve, and it's essential to read its documentation and other in-depth resources to get a comprehensive understanding, especially for more complex projects.
Setting up Dagger 2 for Dependency Injection in Android:
implementation 'com.google.dagger:dagger:2.x' annotationProcessor 'com.google.dagger:dagger-compiler:2.x'Code (Kotlin - Dagger component):
@Component(modules = [AppModule::class]) interface AppComponent { fun inject(app: MyApplication) }
Dagger 2 components and modules in Android:
@Module class AppModule { @Provides fun provideSomeDependency(): SomeDependency { return SomeDependency() } }Code (Kotlin - Dagger component):
@Component(modules = [AppModule::class]) interface AppComponent { fun inject(app: MyApplication) }
Constructor injection with Dagger 2 in Android:
class MyRepository @Inject constructor(private val apiService: ApiService) { // Class logic using injected dependencies }
Scopes and singleton injection with Dagger 2:
@Singleton
for singletons.@Singleton @Component(modules = [AppModule::class]) interface AppComponent { fun inject(app: MyApplication) }
Dagger 2 multibindings in Android:
@Module abstract class MyModule { @Binds @IntoSet abstract fun bindDependency1(impl1: Dependency1): Dependency @Binds @IntoSet abstract fun bindDependency2(impl2: Dependency2): Dependency }
Dagger 2 and Android ViewModel injection:
@Component(modules = [AppModule::class, ViewModelModule::class]) interface AppComponent { fun inject(app: MyApplication) }Code (Kotlin - Dagger module with ViewModel bindings):
@Module abstract class ViewModelModule { @Binds abstract fun bindViewModelFactory(factory: DaggerViewModelFactory): ViewModelProvider.Factory @Binds @IntoMap @ViewModelKey(MyViewModel::class) abstract fun bindMyViewModel(viewModel: MyViewModel): ViewModel }
Dagger 2 and Retrofit integration in Android:
@Module class NetworkModule { @Provides @Singleton fun provideRetrofit(): Retrofit { return Retrofit.Builder() .baseUrl("https://api.example.com/") .addConverterFactory(GsonConverterFactory.create()) .build() } @Provides @Singleton fun provideApiService(retrofit: Retrofit): ApiService { return retrofit.create(ApiService::class.java) } }