Я пытался использовать dagger 2 с android для внедрения зависимостей, но в течение некоторого времени столкнулся с некоторыми проблемами.
Я пытаюсь внедрить два интерфейса ApiHelperInterface и SchedulerProvider для использования в моем классе viewmodel, но объект выполняется с нулевым подтверждением того, что запрошенная инъекция не была завершена.
ниже показывает мой appmodul класс
@Module(includes = ViewModelModule.class)
public class AppModule {
@Singleton
@Provides
Context provideContext(Application application) {
return application;
}
@PreferenceInfo
@Provides
String providePreferenceName() {
return AppConstants.PREF_NAME;
}
@Provides
SchedulerProvider provideSchedulerProvider() {
return new AppSchedulerProvider();
}
@Singleton
@Provides
ApiHelperInterface provideApiHelperInterface(ApiHelper apiHelper) {
return apiHelper;
}
}
Класс ApiHelper и AppschedulerProvider, как показано ниже
@Singleton
public class ApiHelper implements ApiHelperInterface {
@Inject
public ApiHelper(){
}
@Override
public Single<JSONArray> getRocketApiCall() {
return Rx2AndroidNetworking.get(ApiEndPoint.ENDPOINT_Rocket)
.build()
.getJSONArraySingle();
// .getObjectSingle(RocketResponse.class);
}
@Override
public void doLogHere() {
Log.d("Live", "Believing this object might as well be injected");
}
}
public class AppSchedulerProvider implements SchedulerProvider {
@Inject
public AppSchedulerProvider(){
}
@Override
public Scheduler computation() {
return Schedulers.computation();
}
@Override
public Scheduler io() {
return Schedulers.io();
}
@Override
public Scheduler ui() {
return AndroidSchedulers.mainThread();
}
}
Мой класс приложения выглядит ниже
public class SpaceRocketX extends Application implements HasActivityInjector {
@Inject
DispatchingAndroidInjector<Activity> dispatchingAndroidInjector;
@Override
public void onCreate(){
super.onCreate();
DaggerAppComponent.builder()
.application(this)
.build()
.inject(this);
AndroidNetworking.initialize(getApplicationContext());
}
@Override
public AndroidInjector<Activity> activityInjector() {
return dispatchingAndroidInjector;
}
}
Пожалуйста, что я мог сделать неправильно, чтобы вставить нулевой объект, как подсказывает мой стек logcat
Caused by: java.lang.NullPointerException: Attempt to invoke interface method 'void com.example.spacerocketx.remote.ApiHelperInterface.doLogHere()' on a null object reference
at com.example.spacerocketx.view.ui.rocketList.RocketListViewModel.fetchRocketList(RocketListViewModel.java:57)
at com.example.spacerocketx.view.ui.rocketList.RocketListViewModel.<init>(RocketListViewModel.java:48)
RocketViewModel class
public class RocketListViewModel extends ViewModel {
@Inject
public ApiHelperInterface apiHelperInterface;
@Inject
public SchedulerProvider schedulerProvider;
private LiveData<List<Rocket>> rocketListObservable;
private final RocketResponse rocketResponse = new RocketResponse();
private final CompositeDisposable mCompositeDisposable = new CompositeDisposable();
@Inject
public RocketListViewModel(){
Log.d("LiveConstruct", "It is working here just with empty viewmodel as demanded");
new RocketListViewModel(apiHelperInterface, schedulerProvider);
}
// @Inject
public RocketListViewModel(@NonNull ApiHelperInterface apiHelperInterface, @NonNull SchedulerProvider schedulerProvider) {
// this.apiHelperInterface = apiHelperInterface;
// this.schedulerProvider = schedulerProvider;
rocketListObservable = fetchRocketList(apiHelperInterface, schedulerProvider);
}
private LiveData<List<Rocket>> fetchRocketList(ApiHelperInterface apiHelperInterface, SchedulerProvider schedulerProvider) {
final MutableLiveData<List<Rocket>> data = new MutableLiveData<>();
apiHelperInterface.doLogHere();
mCompositeDisposable.add(apiHelperInterface
.getRocketApiCall()
.subscribeOn(schedulerProvider.io())
.observeOn(schedulerProvider.ui())
.subscribe(rocketResponse -> {
if(rocketResponse != null && rocketResponse.length() > 0){
Log.d("LiveData", rocketResponse.toString());
this.rocketResponse.setRocketList((List<Rocket>) rocketResponse);
data.setValue(this.rocketResponse.getRocketList());
}
}, throwable -> {
// TODO:
}
));
return data;
}
public LiveData<List<Rocket>> getRocketListObservable() {
return rocketListObservable;
}
}
Фрагмент моего списка выглядит следующим образом
public class RocketListFragment extends Fragment implements Injectable {
public static final String TAG = "RocketListFragment";
private RocketAdapter rocketAdapter;
private FragmentRocketListBinding binding;
@Inject
ViewModelProvider.Factory viewModelFactory;
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container,
@Nullable Bundle savedInstanceState) {
binding = DataBindingUtil.inflate(inflater, R.layout.fragment_rocket_list, container, false);
rocketAdapter = new RocketAdapter(rocketClickCallback);
binding.rocketList.setLayoutManager(new LinearLayoutManager(getActivity()));
binding.rocketList.setAdapter(rocketAdapter);
binding.setIsLoading(true);
return binding.getRoot();
}
@Override
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
final RocketListViewModel viewModel = ViewModelProviders.of(this, viewModelFactory).get(RocketListViewModel.class);
observeViewModel(viewModel);
}
private void observeViewModel(RocketListViewModel viewModel) {
// Update the list when the data changes
if(viewModel != null){
Log.d("VM", "ViewModel is not null at all");
viewModel.getRocketListObservable().observe(this, rockets -> {
if (rockets != null) {
binding.setIsLoading(false);
rocketAdapter.setRocketList(rockets);
}
});
}
}
private final RocketClickCallback rocketClickCallback = new RocketClickCallback() {
@Override
public void onClick(Rocket project) {
if (getLifecycle().getCurrentState().isAtLeast(Lifecycle.State.STARTED)) {
// ((MainActivity) getActivity()).show(project);
}
}
};
}