I'm trying to inject Glide with Dagger.
So I have AppModule:
@Module
class AppModule {
@Provides
fun provideRequestOptions(): RequestOptions {
return RequestOptions()
.placeholder(R.drawable.white_background)
.error(R.drawable.white_background)
}
@Provides
fun provideGlideInstance(application: Application, requestOptions: RequestOptions): RequestManager{
return Glide.with(application).setDefaultRequestOptions(requestOptions)
}
@Nullable
@Provides
fun provideAppDrawable(application: Application): Drawable? {
return ContextCompat.getDrawable(application, R.drawable.logo)
}
}
And AuthActivity:
class AuthActivity : DaggerAppCompatActivity() {
lateinit var binding: ActivityAuthBinding
@Inject
lateinit var logo: Drawable
@Inject
lateinit var requestManager: RequestManager
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityAuthBinding.inflate(layoutInflater)
setContentView(binding.root)
setLogo()
}
private fun setLogo() {
requestManager.load(logo).into(binding.loginLogo)
}
}
provideAppDrawable()
in AppModule has to return nullable Drawable?
. When I'm trying to build app, Dagger complains about its nullability:
\AppComponent.java:7: error: [Dagger/Nullable] android.graphics.drawable.Drawable is not nullable, but is being provided by @org.jetbrains.annotations.Nullable @androidx.annotation.Nullable @Provides android.graphics.drawable.Drawable com.example.daggercodingwithmitch.di.AppModule.provideAppDrawable(android.app.Application)
public abstract interface AppComponent extends dagger.android.AndroidInjector<com.example.daggercodingwithmitch.BaseApplication> {
First I tried to make logo
var in AuthActivity
nullable, but lateinit can't be nullable. And if I don't use lateinit and make sth like this: var logo: Drawable? = null
I get strange error abount private field injection even though it is not private:
\AuthActivity.java:10: error: Dagger does not support injection into private fields
private android.graphics.drawable.Drawable logo;
How can I fix it? Thx.
Easiest way is to make provideAppDrawable return a Drawable instead of a Drawable? and remove the @Nullable from it. Is there any scenario under which that returns null which isn't a bug? If not, it shouldn't be a nullable variable.