I am facing an issue when injecting the retrofit service object using dagger2. Here is the details of my scenario:
Retrofit WebService Class:
public interface WebService {
Observable<Name> searchName(@Query("id") String id);
}
Here is SubModule class:
@Module
public class SetupModule {
@Provides
MainActivity provideWebService(WebService webService) {
return new MainActivity(webService);
}
}
Here is SubComponent class:
@SetupScope
@Subcomponent(modules = SubModule.class)
public interface SubComponent {
MainActivity inject(MainActivity mainActivity);
}
Here is AppComponent Class:
@Singleton
@Component(modules = {
AppModule.class,
NetworkModule.class})
public interface AppComponent
{
SubComponent plus(SubModule subModule);
}
Here is the component creation in BaseApplication Class:
public SubComponent createSubComponent()
{
subComponent = appComponent.plus(new subModule());
return subComponent;
}
Here is the MainActivity class:
public MainActivity(WebService webService) {
this.webService = webService;
}
@Override
protected void onCreate(Bundle savedInstanceState) {
((BaseApplication) getApplication()).createSubComponent().inject(this);
}
I am getting the webservice nullpointerexception
when trying to access the searchName method in WebService interface from MainActivity.
Please help me to find out why webservice object getting null?
I think, at first you should remove WebService from activity constructor, and initiate service something like that:
@Inject
WebService webService;
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.