Android — Content Providers + Dependency Injection (Dagger 2)

My “How can I do it?” reaction
My “Is that possible?” reaction
// In my case I used 2.16 version
implementation 'com.google.dagger:dagger-android:[DaggerVersion]'
class App : Application(), HasActivityInjector, HasContentProviderInjector {

@Inject
lateinit var androidInjector: DispatchingAndroidInjector<Activity>

@Inject
lateinit var contentProviderInjector: DispatchingAndroidInjector<ContentProvider>


override fun activityInjector() = androidInjector

override fun contentProviderInjector() = contentProviderInjector

override fun attachBaseContext(base: Context?) {
super.attachBaseContext(base)
setupDependencyInjection()
}

/**
* Injects the app component
*/
private fun setupDependencyInjection() {
DaggerAppComponent.builder().application(this).build().inject(this)
}

}
class VoIPAppProvider: ContentProvider() {

@Inject
lateinit var databaseHelper: DatabaseHelper


override fun onCreate(): Boolean {
AndroidInjection.inject(this)
return true
}

override fun insert(uri: Uri?, contentValues: ContentValues?): Uri? {
...
return uri
}

override fun query(uri: Uri?, projection: Array<out String>?, selection: String?, selectionArgs: Array<out String>?, sortOrder: String?): Cursor {
...
return cursor
}

override fun getType(uri: Uri?): String {
...
return type
}
override fun update(uri: Uri?, contentValues: ContentValues?, selection: String?, selectionArgs: Array<out String>?): Int {
...
return rowsUpdated
}

override fun delete(uri: Uri?, selection: String?, selectionArgs: Array<out String>?): Int {
...
return rowsDeleted
}
}
Woooow! We did it!

--

--

Android Engineer @TripAdvisor

Love podcasts or audiobooks? Learn on the go with our new app.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store