将dataSource类注入presenter会给出null

时间:2016-09-29 15:35:39

标签: android dagger-2

我正在尝试使用Dagger 2将DataSource类注入Presenter,但dataSource为空。

代码如下:

public class MainPresenter implements MainMVP.Presenter {

public static final String TAG = "MAIN-PRESENTER";

@NonNull
private MainMVP.View mainView;

@Inject
DataSource dataSource;

public MainPresenter(@NonNull MainMVP.View mainView) {
    this.mainView = mainView;

    Log.i(TAG, "MainPresenter init");
    DaggerDataComponent.builder()
            .dataModule(new DataModule())
            .build();
}

@Override
public void onButtonClick() {
    if (dataSource != null) {
        mainView.showData(dataSource.getReleaseString());
    }
}

} 

如果我删除了在dataSource中检查null的条件,我得到NullPointerException。任何人都可以帮忙吗?构造函数不是构建DataComponent的正确位置吗?

1 个答案:

答案 0 :(得分:1)

您正在构建组件,但您似乎并没有真正使用它。

DataCompontent component = DaggerDataComponent.builder()
            .dataModule(new DataModule())
            .build();
component.inject(this);

并添加

void inject(MainPresenter presenter);

到您的DataComponent界面。

关于你是否是构建组件的正确位置的问题:我们无法真正回答这个问题。这很大程度上取决于您的代码架构。

Here's a nice example of MVP + dagger2 architecture.也许可以尝试一下。

相关问题