Dagger Hilt Android Example kotlin

01-Jan-2025

Dagger Hilt Android Example kotlin

To understand the concept we use the same example where a Car class depends on an Engine class.


1/  Create A New Project.



2/ Modify build.gradle.kts (app level)


add -> 

               id("kotlin-kapt")

       id("dagger.hilt.android.plugin")

add -> below two dependency
       implementation("com.google.dagger:hilt-android:2.51.1")

       kapt("com.google.dagger:hilt-android-compiler:2.51.1")



plugins {
alias(libs.plugins.android.application)
alias(libs.plugins.kotlin.android)
id("kotlin-kapt")
id("dagger.hilt.android.plugin")
}

android {
namespace = "com.zissofworks.daggerhiltandroidexamplekotlin"
compileSdk = 35

defaultConfig {
applicationId = "com.zissofworks.daggerhiltandroidexamplekotlin"
minSdk = 28
targetSdk = 34
versionCode = 1
versionName = "1.0"

testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner"
}

buildTypes {
release {
isMinifyEnabled = false
proguardFiles(
getDefaultProguardFile("proguard-android-optimize.txt"),
"proguard-rules.pro"
)
}
}
compileOptions {
sourceCompatibility = JavaVersion.VERSION_1_8
targetCompatibility = JavaVersion.VERSION_1_8
}
kotlinOptions {
jvmTarget = "1.8"
}
}

dependencies {

implementation(libs.androidx.core.ktx)
implementation(libs.androidx.appcompat)
implementation(libs.material)
implementation(libs.androidx.activity)
implementation(libs.androidx.constraintlayout)
testImplementation(libs.junit)
androidTestImplementation(libs.androidx.junit)
androidTestImplementation(libs.androidx.espresso.core)

implementation("com.google.dagger:hilt-android:2.51.1")
kapt("com.google.dagger:hilt-android-compiler:2.51.1")
}




3/ Modify build.gradle.kts (project level)


add ->   id("com.google.dagger.hilt.android") version "2.51.1" apply false



// Top-level build file where you can add configuration options common to all sub-projects/modules.
plugins {
alias(libs.plugins.android.application) apply false
alias(libs.plugins.kotlin.android) apply false
id("com.google.dagger.hilt.android") version "2.51.1" apply false
}




4/ Create a class Engine with @Inject annotation



package com.zissofworks.daggerhiltandroidexamplekotlin

import android.util.Log
import javax.inject.Inject

class Engine @Inject constructor() {
fun start(){
Log.d("DaggerHiltExample", "Engine Start")
}
}



5/  Create a class Car with @Inject annotation and this class is dependent on the Engine class taking the Engine class object as a parameter



package com.zissofworks.daggerhiltandroidexamplekotlin

import android.util.Log
import javax.inject.Inject

class Car @Inject constructor(private val engine: Engine) {
fun drive(){
engine.start()
Log.d("DaggerHiltExample", "car drive")
}
}



6/ Create a class MyApplication which extends the Application. Annotation this class with @HiltAndroidApp  and add on manifest file.


It ensures that the hilt is properly initialized for your application. And this step is mandatory.



package com.zissofworks.daggerhiltandroidexamplekotlin

import android.app.Application
import dagger.hilt.android.HiltAndroidApp

@HiltAndroidApp
class MyApplication : Application() {

}



7/ Add the MyApplication in AndroidManifest.xml file application tag



<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools">

<application
android:name=".MyApplication"
android:allowBackup="true"
android:dataExtractionRules="@xml/data_extraction_rules"
android:fullBackupContent="@xml/backup_rules"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/Theme.DaggerHiltAndroidExampleKotlin"
tools:targetApi="31">
<activity
android:name=".MainActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />

<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>

</manifest>



8/ Modify MainActivity.Kt

   here we just add the variable for the Car object and never initialize or create the object. Dagger will provide the instance of Car by the @Inject annotation. We don't need to do it manually. 

Annotation with
 @AndroidEntryPoint with this activity.



package com.zissofworks.daggerhiltandroidexamplekotlin

import android.os.Bundle
import androidx.activity.enableEdgeToEdge
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import dagger.hilt.android.AndroidEntryPoint
import javax.inject.Inject

@AndroidEntryPoint
class MainActivity : AppCompatActivity() {

@Inject
lateinit var car: Car

override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
enableEdgeToEdge()
setContentView(R.layout.activity_main)
ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main)) { v, insets ->
val systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars())
v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom)
insets
}

car.drive()
}
}





Comments