Mes Mes - 2 months ago 13
Android Question

Injecting dataSource class to presenter gives null

I'm trying to inject

DataSource
class to
Presenter
using Dagger 2, but dataSource is null.

The code is below :

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

}


If I remove the condition that checks for null in dataSource I'm getting a
NullPointerException
. Anyone can help with that? Isn't the constructor the right place to build the
DataComponent
?

Answer

You're building your component but you don't seem to be actually using it.

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

and add

void inject(MainPresenter presenter);

to your DataComponent interface.


As for your question about if that is the right place to build your component: we can't really answer that. That strongly depends on your code architecture.

Here's a nice example of MVP + dagger2 architecture. Maybe try following that.