I'm trying to use Dagger 2 in my applications, but I had problems with the entity repository, and I did not understand what I was missing.
Here is my application component:
@Singleton
@Component(
modules = {
AndroidModule.class,
RepositoryModule.class
}
)
public interface ApplicationComponent {
void inject(AndroidApplication app);
IDependenceyRepository dependencyRepository();
}
My modules:
@Module
public class RepositoryModule {
@Provides @Singleton IDependenceyRepository provideDependendencyRepository(Context context) {
return new DependencyRepository(context);
}
}
@Module
public class AndroidModule {
private final AndroidApplication app;
public AndroidModule(AndroidApplication app) {
this.app = app;
}
@Provides @Singleton Context provideApplicationContext() {
return app;
}
}
My AndroidApplication:
public class AndroidApplication extends Application {
private ApplicationComponent component;
@Override
public void onCreate() {
super.onCreate();
setupGraph();
}
private void setupGraph() {
component = DaggerApplicationComponent.builder()
.androidModule(new AndroidModule(this))
.repositoryModule(new RepositoryModule())
.build();
component.inject(this);
}
public ApplicationComponent component() {
return component;
}
}
And here is my activity:
public class MainActivity extends Activity {
@Inject
IDependenceyRepository repository;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
this.testRepository();
}
private void testRepository() {
Dependency dep = new Dependency();
dep.setDescription("XXX");
dep.setName("AAAA");
try {
repository.save(dep);
Log.d("", repository.queryAll().get(0).getName());
} catch (SQLException e) {
e.printStackTrace();
}
}
What happens is that I get a null pointer exception in the repository. It is not administered.
If I add this line, then:
repository = ((AndroidApplication) getApplication()).component().dependencyRepository();
This works, but the DI point should not worry about it, or am I mistaken about it?
I tried another example and tutorials, but I was not able to solve my problem.
Thanks in advance,
source
share