How to Implement Hilt in Android App? | Hilt using Shared preference and Image Loader
Dependency injection (DI) is a technique widely used in programming and well suited to Android development. By following the principles of DI, you lay the groundwork for good app architecture.
Implementing dependency injection provides you with the following advantages:
- Reusability of code
- Ease of refactoring
- Ease of testing
Dependency injection library is hard to use, this article provides the simple and easy to follow steps to Implement Hilt in your Android app.
// Top-level build file where you can add configuration options common to all sub-projects/modules.
buildscript {
dependencies {
classpath("com.google.dagger:hilt-android-gradle-plugin:2.44")
}
}
plugins {
...
}
plugins {
...
id 'kotlin-kapt'
id 'dagger.hilt.android.plugin'
}
dependencies {
// Dagger Hilt
implementation 'com.google.dagger:hilt-android:2.44'
kapt 'com.google.dagger:hilt-compiler:2.44'
// Picasso : To load image
implementation 'com.squareup.picasso:picasso:2.71828'
}
@HiltAndroidApp
class MyApplication: Application()
<manifest>
<application
android:name=".MyApplication"
...
</application>
</manifest>
@AndroidEntryPoint
class MainActivity : AppCompatActivity() {
...
}
@AndroidEntryPoint
class FirstFragment : Fragment() {
...
}
@AndroidEntryPoint
class FirstFragment : Fragment() {
@Inject
lateinit var picassoUtil: PicassoUtil
override fun onCreateView(
...
}
class PicassoUtil @Inject constructor(private val picasso: Picasso) {
fun loadImage(imageUrl: String, imageView: ImageView) {
picasso.load(imageUrl).into(imageView)
}
}
@Module
@InstallIn(SingletonComponent::class)
object PicassoModule {
@Provides
fun providesPicasso(): Picasso {
return Picasso.get()
}
}
The components used are shown in the table below:
Component | Injector for |
---|---|
SingletonComponent | Application |
ViewModelComponent | ViewModel |
ActivityComponent | Activity |
FragmentComponent | Fragment |
ViewComponent | View |
ViewWithFragmentComponent | View with @WithFragmentBindings |
ServiceComponent | Service |
Comments
Post a Comment