在使用(MVVM)请求的类对象的情况下,注入的字段返回null

时间:2019-06-08 00:28:26

标签: java android dependency-injection dagger-2

我一直在尝试将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类

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);
            }
        }
    };

}

1 个答案:

答案 0 :(得分:0)

您应该在ViewModel构造函数中取消注释此行。

this.apiHelperInterface = apiHelperInterface;
this.schedulerProvider = schedulerProvider;

您正在使用apiHelperInterface,但尚未初始化它。