【问题标题】:Method injection dagger2 null exception when asking for the dependency请求依赖时方法注入dagger2 null异常
【发布时间】:2018-11-23 15:45:54
【问题描述】:

嗨,我正在尝试使用 dagger 2 的方法注入,并且在使用注入的依赖项时出现空指针异常我尝试删除 @provide 注释并在此处的单独模块中提取 DialogManger

@Module

公共类 DialogManagerModule {

Context context;

public DialogManagerModule(Context context){
    this.context = context;
}

@Provides
DialogManager provideDialogManager(Context context){
    return new DialogManager(context);
}

@Provides
ProgressDialogInteractor provideProgressDialogInteractor(){
    return new ProgressDialog();
}

@Provides
Context provideContext(){
    return context;
}

}

public class DialogManager {

Context context;

ProgressDialogInteractor progressDialog;

@Inject
public void setProgressDialog(ProgressDialogInteractor progressDialog) {
    this.progressDialog = progressDialog;
}

public DialogManager(Context context) {
    this.context = context;
}

public void showDatePickerDialog(DatePickerDialog.OnDateSetListener listener){
    Calendar calendar = Calendar.getInstance();
     new DatePickerDialog(
            context
             , listener
             , calendar.get(Calendar.YEAR)
             , calendar.get(Calendar.MONTH)
             , calendar.get(Calendar.DAY_OF_MONTH))
             .show();
}

public void showProgressDialog(@Nullable String progressText){

    progressDialog
           /* .setText(progressText)
            .showText()*/
            .show();

}

}

这里是我如何调用组件

component =((App) getActivity().getApplication()).getComponent()
            .newPersonalInfoFragmentComponent(new PersonalInfoFragmentModule(this), new DialogManagerModule(getContext()));

【问题讨论】:

    标签: android dagger-2


    【解决方案1】:

    您应该在 ContextModule 类中提供您的上下文,并且您必须提供您在提供方法中使用的所有对象。

    @Singleton
    @Module
    public abstract class ContextModule {
    
        @Binds
        abstract Context provideContext(Application application);
    }
    

    【讨论】:

      猜你喜欢
      • 2018-01-19
      • 1970-01-01
      • 1970-01-01
      • 2019-02-25
      • 2021-08-01
      • 1970-01-01
      • 2022-11-12
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多