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 with Dagger 2 in Android

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:

1. Add Dependencies:

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'

2. Set Up Components and Modules:

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
}

3. Initialize Dagger in 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.

4. Inject Dependencies:

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

5. Dagger Android:

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.

Note:

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.

  1. Setting up Dagger 2 for Dependency Injection in Android:

    • Description: Configure Dagger 2 in your Android project by adding dependencies and setting up the Dagger component.
    • Code (build.gradle):
      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)
      }
      
  2. Dagger 2 components and modules in Android:

    • Description: Define Dagger components and modules to organize dependency injection. Components are responsible for injecting dependencies, while modules provide the dependencies.
    • Code (Kotlin - Dagger module):
      @Module
      class AppModule {
          @Provides
          fun provideSomeDependency(): SomeDependency {
              return SomeDependency()
          }
      }
      
      Code (Kotlin - Dagger component):
      @Component(modules = [AppModule::class])
      interface AppComponent {
          fun inject(app: MyApplication)
      }
      
  3. Constructor injection with Dagger 2 in Android:

    • Description: Use constructor injection to inject dependencies directly into a class's constructor.
    • Code (Kotlin - Class with constructor injection):
      class MyRepository @Inject constructor(private val apiService: ApiService) {
          // Class logic using injected dependencies
      }
      
  4. Scopes and singleton injection with Dagger 2:

    • Description: Apply scopes to control the lifecycle of injected dependencies, and use @Singleton for singletons.
    • Code (Kotlin - Dagger component with scope):
      @Singleton
      @Component(modules = [AppModule::class])
      interface AppComponent {
          fun inject(app: MyApplication)
      }
      
  5. Dagger 2 multibindings in Android:

    • Description: Use Dagger 2 multibindings to inject sets or maps of dependencies.
    • Code (Kotlin - Dagger module with multibindings):
      @Module
      abstract class MyModule {
          @Binds
          @IntoSet
          abstract fun bindDependency1(impl1: Dependency1): Dependency
      
          @Binds
          @IntoSet
          abstract fun bindDependency2(impl2: Dependency2): Dependency
      }
      
  6. Dagger 2 and Android ViewModel injection:

    • Description: Inject dependencies into Android ViewModels using Dagger 2.
    • Code (Kotlin - Dagger component with 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
      }
      
  7. Dagger 2 and Retrofit integration in Android:

    • Description: Integrate Dagger 2 with Retrofit for dependency injection in Android networking components.
    • Code (Kotlin - Dagger module with Retrofit):
      @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)
          }
      }