我上课了
public class DialogUtils { private Context context; @Inject public DialogUtils(Context context) { this.context = context; } }
在我的活动类中我已经做了但是我在dialogUtils实例上得到空指针异常.
public class LoginActivity extends Activity{ @Inject DialogUtils dialogUtils; }
我知道如何通过模块和组件注入依赖,但不知道如何使用构造注入.任何帮助深表感谢.
解决方法
如果您没有保留活动级别组件,并且您没有使用组件依赖关系或子组件继承超级作用域(应用程序级组件),那么它是以下内容
// unscoped public class DialogUtils { private final Context context; @Inject public DialogUtils(Context context) { this.context = context; } }
然后
@Module public class ActivityModule { private final Context context; public ActivityModule (Context context) { this.context = context; } @Provides //scope is not necessary for parameters stored within the module public Context context() { return context; } } @Component(modules={ActivityModule.class}) @Singleton public interface ActivityComponent { Context context(); DialogUtils dialogUtils(); void inject(MainActivity mainActivity); }
然后
@Inject DialogUtils dialogUtils; ... ActivityComponent activityComponent = DaggerMainActivityComponent.builder() .activityModule(new ActivityModule(MainActivity.this)) .build(); activityComponent.inject(this); // activityComponent.dialogUtils() also works