'Dagger 2 @Inject return Null
I am creating multi module android project using java. I got Null when I inject a class.
Followings are my codes.
SignupComponent.class
@FeatureScope
@Subcomponent(modules = SignupModule.class)
public interface SignupComponent {
@Subcomponent.Factory
interface Factory{
SignupComponent create();
}
void inject(Activity_Signup activity_signup);
SignupModule.class
@Module
public class SignupModule {
@FeatureScope
@Provides
public SignupContract.Presenter providePresenter(){
return new SignupPresenter();
}
}
Activity_Signup.class
SignupComponent signupComponent = ((SignupComponentProvider) getApplicationContext())
.provideSignupComponent();
//Inject the view
signupComponent.inject(this);
SignupPresenter.class
public class SignupPresenter implements SignupContract.Presenter {
// this injection return Null
@Inject
public SignupUseCase signupUseCase;
}
SignupUseCase.class
public class SignupUseCase {
@Inject
public SignupUseCase(){}
...
}
Why am I getting NPE?
EDIT
SignupModule.class
@Module
public class SignupModule {
@FeatureScope
@Provides
public SignupContract.Presenter providePresenter(){
return new SignupPresenter();
}
@FeatureScope
@Provides
public SignupUseCase provideUseCase(){
return new SignupUseCase();
}
}
Solution 1:[1]
@FeatureScope
@Provides
public SignupContract.Presenter providePresenter(){
return new SignupPresenter();
}
When you call new SignupPresenter(), Dagger isn't instantiating the object, you are. Therefore, Dagger doesn't inject the @Inject-annotated fields, because it assumes you want the object exactly as you returned it.
If you want Dagger to populate SignupUseCase, you'll need to do one of the following:
Let Dagger create SignupPresenter and receive it in your
@Providesmethod. You'll need to add an@Inject-annotated constructor to SignupPresenter, potentially with no args.@FeatureScope @Provides public static SignupContract.Presenter providePresenter(SignupPresenter presenter) { return presenter; }Let Dagger create SignupPresenter and bind it to SignupContract.Presenter using a
@Bindsmethod. This requires the@Inject-annotated constructor on SignupPresenter and also requires making your Module an abstract class.@FeatureScope @Binds abstract SignupContract.Presenter providePresenter(SignupPresenter presenter);Use a MembersInjector, which you can get via injection. You probably don't want this one unless you're receiving an instance of SignupPresenter that you can add
@Injectmethods and fields to, but that Dagger can't create.@FeatureScope @Provides public static SignupContract.Presenter providePresenter( MembersInjector<SignupPresenter> injector) { SignupPresenter presenter = new SignupPresenter(); injector.injectMembers(presenter); return presenter; }
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Jeff Bowman |
