Dagger 2不初始化变量

时间:2016-03-16 08:21:08

标签: java android dagger-2

现在我正在尝试在我的项目中实施匕首,我有一个问题。在应用程序组件中初始化的变量未在我的活动中初始化。这是我的代码。 应用程序:

public class MyApplication extends Application {
    private ApplicationComponent applicationComponent;
    @Inject
    public Context context;

    @Override
    public void onCreate() {
        super.onCreate();
        applicationComponent = DaggerApplicationComponent.builder().applicationModule(new ApplicationModule(this)).build();
        applicationComponent.inject(this);
    }

    public ApplicationComponent getApplicationComponent() {
        return applicationComponent;
    }
}

这里变量context!= null

的活动:

public class MainActivity extends AppCompatActivity {
    private ActivityComponent activityComponent;
    @Inject
    Context context;

    @Override
    protected void onStart() {
        super.onStart();
        activityComponent = DaggerActivityComponent.builder()
                .activityModule(new ActivityModule(this))
                .applicationComponent(((MyApplication) getApplication()).getApplicationComponent())
                .build();
        activityComponent.inject(this);
    }
}

这里的上下文== null。

匕首:

@Component(modules = {ApplicationModule.class})
public interface ApplicationComponent {
    void inject(MyApplication application);
    Context getApplicationContext();
}

@Component(modules = {ActivityModule.class}, dependencies = {ApplicationComponent.class})
public interface ActivityComponent {
    void inject(MainActivity mainActivity);
}

@Module
public class ApplicationModule {
    private Application application;

    public ApplicationModule(MyApplication application) {
        this.application = application;
    }

    @Provides
    Context provideApplicationContext() {
        return application.getApplicationContext();
    }
}

@Module
public class ActivityModule {
    Activity activity;

    public ActivityModule(MainActivity activity) {
        this.activity = activity;
    }
}

因此,dagger仅在应用程序类中提供“Context”,但不在MainActivity类中提供它。我做错了什么?可能是我必须改变一些事情。

谢谢!

2 个答案:

答案 0 :(得分:0)

像这样设置:

public class MyApplication extends Application {
  private ApplicationComponent applicationComponent;

  @Override
  public void onCreate() {
    super.onCreate();
    applicationComponent = DaggerApplicationComponent.builder()
            .applicationModule(new ApplicationModule(this))
            .build();
  }

  public ApplicationComponent getApplicationComponent() {
    return applicationComponent;
  }
}

和您的活动:

public class MainActivity extends AppCompatActivity {

  @Inject
  Context context;

  @Override
  protected void onStart() {
    super.onStart();
    ((MyApplication) getApplication()).getApplicationComponent().inject(this);
  }
}

答案 1 :(得分:0)

老实说,这只是猜测,但你应该尝试确定组件的范围。

matrixB(locnew + m*(0:(n-1))) = 0