Android, Using AppModule context at whole the app using dagger 2 - android

According code below:
#Module
public class AppModule {
private Application application;
public AppModule(Application application) {
this.application = application;
}
#Singleton
#Provides
Context providesContext() {
return application;
}
#Singleton
#Provides
IAppDbHelper providesAppDbHelper() {
// a SQLiteOpenHelper class
return new AppDbHelper(application);
}
}
AppComponent:
#Singleton
#Component(modules = AppModule.class)
public interface AppComponent {
void inject(MainActivity mainActivity);
void inject(SecondActivity secondActivity);
IAppDBHelper providesIAppDBHelper();
}
MainActivity:
public class MainActivity extends AppCompatActivity {
#Inject
IAppDBHelper helper;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
((MyApplication)getApplication()).getComponent()
.inject(this);
// It's OK
helper.getWritable().execSQL("XXX");
startActivity(new Intent(MainActivity.this, SecondActivity.class));
}
}
SecondActivity:
public class SecondActivity extends AppCompatActivity {
#Inject
IAppDBHelper helper;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_test);
// nullPointer on helper
helper.getWritable().execSQL("XXX");
}
}
After injecting my AppComponent inside my SecondActivity, nullPointer error fixes but my question is do I have to inject My AppComponent every time I want inject IAppDbHelper? So what does #Singleton and injecting in inside my MainActivity mean? Doesn't should they inject that IAppDbHelper for my SecondActivity?

You will need to get your component and inject each class that Android creates. This typically means all Activities, Fragments, and Views. Dagger can't create those classes, so the only way Dagger knows about the externally-created instance is when you pass it into the inject method on your Component.
During the injection, all #Inject fields on MainActivity and SecondActivity will be provided, and any instances that Dagger creates will also have their dependencies injected, and so forth all the way down the line. This means that you won't usually need your Component directly outside of your externally-created classes like Activities and Fragments, or (of course) your Application instance where you create the Component instance itself.
#Singleton does mean that the instance will remain the same between MainActivity, SecondActivity, and any future instances of MainActivity or SecondActivity that Android may create as you background the app. However, you still need to request injection for those classes as Android creates them, in order to receive that same instance that you've guaranteed with #Singleton.

Related

Dagger 2 Getting null object reference on create method

I can't understand what wrong I am doing here
Splash Activity :
public class SplashActivity extends BaseActivity implements SplashView {
#Inject
SplashPresenter presenter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_splash_with_di);
presenter.getAppVersion();
}
}
Component :
#Component(modules = SplashModule.class)
public interface AppComponent {
SplashWithDiPresenter getSplashWithDiPresenter();
}
Splash Module :
#Module(includes = RetrofitModule.class)
public class SplashModule {
#Provides
SplashPresenter provideSplashPresenter(final SplashInteractorImpl interactor){
return new SplashPresenterImpl(interactor);
}
#Provides
SplashInteractor providesSplashInteractor(final ApiInterface apiInterface){
return new SplashWithDiInteractorImpl(apiInterface);
}
}
inside application class called this method in onCreate()
private void createComponent() {
appComponent = DaggerAppComponent.builder()
.splashModule(new SplashModule())
.build();
}
Getting null object reference on Splash activity on create method
-> presenter.getAppVersion();
You have injected your application dependencies and now you need to do the same with SplashActivity dependencies. So you need to create a new component for your activity, lets say SplashComponent, and add inject method to it like this:
#PerActivity
#Component(modules = SplashModule.class, dependencies = AppComponent.class)
public interface SplashComponent {
public void inject(SplashActivity activity);
}
And then in your SplashActivity in the onCreate method add injection like this:
public class SplashActivity extends BaseActivity implements SplashView {
#Inject
SplashPresenter presenter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_splash_with_di);
DaggerSplashComponent.builder()
.appComponent(getAppication().getAppComponent())
.splashModule(new SplashModule())
.build()
.inject(this);
presenter.getAppVersion();
}
}
Note, that you need to call your presenter's method only after you have injected your dependencies with inject method!
Ideally you should look at using subcomponents for these use cases for injecting Android Components(Activities, Fragments, Services...). It's pretty simple and avoids coupling Injector Components with Android components enabling testing of these classes and switching of components for Espresso tests.
Add dagger-android deps to your project (com.google.dagger:dagger-android-support:2.x, com.google.dagger:dagger-android-processor:2.x)
And then make an abstract DepsModule module, for example -
#Module
public abstract class DepsModule {
#PerActivity
#ContributesAndroidInjector(modules={SplashModule.class})
SplashActivity provideSplashInjector()
}
And change you App Component to include AndroidSupportInjectionModule.class & DepsModule.class and you should remove SplashModule.classs from the list to avoid rebinding errors.
Now its as easy as having a DispatchingAndroidInjector<Activity> instance injected to you App class and implementing HasActivityInjector interface to return the dispatching injector.
Now in SplashActivity before invoking super.onCreate() call AndroidSupportInjection.inject(this)
#ContribbutesAndroidInjector automatically tells dagger to create a sub-component for SplashActivity and bind the injector factory with DispatchingAndroidInjector<Activity> removing the need for boilerplate sub-component classes
And other sub-component installations for different activities can be added to DepsModule to enable injecting them in a similar way.
This also helps in scope segregation as exposing a splash activity's bindings to the entire app component is not really good
Hope I could help. You can visit the dagger 2 android docs for more info on using Dagger 2

Injecting Singleton class using Dagger 2.x

I have two components, one for Application Context and one for Activity Context as shown below.
#Singleton
#Component(modules = {AppModule.class,})
public interface AppComponent {
#ForApplication
Context context();
//Preferences prefs(); //(Question is related to this line)
}
#PerActivity
#Component(dependencies = AppComponent.class,modules = {ActivityModule.class})
public interface ActivityComponent extends AppComponent {
void inject(ActivityA activity);
}
I have a Singleton class that I want to inject in ActivityA that is declared in ActivityComponent.
#Singleton
public class Preferences {
#Inject
public Preferences(#ForApplication Context context) {
...
}
}
public class ActivityA extends AppCompatActivity {
#Inject
Preferences preferences;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
DaggerActivityComponent.builder()
.appComponent(((MyApplication) getApplication()).getComponent())
.activityModule(new ActivityModule(this))
.build();
}
I am injecting AppComponent in my Applicaiton onCreate() and ActivityComponent in onCreate of Activity, in this case ActivityA like above
Problem(or Question): Currently, If I do not expose this singleton class from my AppComponent (The commented line in first code block) and do not have provides method in AppModule. I cannot compile. Compilation Error shows I cannot have a reference to different scope from ActivityComponent, which I kind of understand. That means, I cannot access Singleton scoped class with PerActivity scoped component.
But, do I have to have provides method for all Singleton class and expose it via AppComponent (which I am currently doing and works)? Is there a better way to do the Singleton class injection?
There is another way. Declare Activity component as Application subcomponent. This way everything declared in Application component is visible in Activity subcomponent.
Access to the Activity subcomponent can be done through Acpplication component:
GithubClientApplication.get(this)
.getAppComponent()
.provide(new ActivityModule(this))
Have a look at this excellent article about Dagger components, especially in Implementation section.

Dagger 2 component inheritance and errors

I'm trying to create the following scenario:
public interface DaggerInjectionFactory {
void inject(MyActivity myActivity);
}
#Singleton
#Component(modules = {RestModule.class})
public interface MyRestComponent extends DaggerInjectionFactory {
RestClient provideRestClient();
}
#Singleton
#Component(modules = {PreferencesModule.class})
public interface MyPreferencesComponent extends DaggerInjectionFactory {
SharedPreferences provideSharedPreferences();
}
The dagger compiler gives me the following error as a response:
error: RestClient cannot be provided without an #Provides- or #Produces-annotated method.
The RestModule contains a #Provides #Singleton RestClient provideRestClient() method and it is also worth noting that when I remove the extends DaggerInjectionFactory from the MyPreferencesComponent the dagger compiler has no issue in generating the component builders.
What I'm trying to do is create an interface with all the injectable classes, in which I want to use the #Inject annotation, and implement them in 'all' of my components so I don't have to add the void inject(MyActivity myActivity); to all of my components.
Because I'm new to the framework I have no idea what the correct terminology is and therefore have no real clue as to what I need to search for.
So my questions are: is it possible to create such a structure, to define an interface which automatically adds all the void inject() methods to 'all' of my components? and if so, how can it be done?
-- Edit --
The expected usage would be something like:
public MyActivity extends Activity {
private RestClient restClient;
private SharedPreferences sharedPreferences;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
MyRestComponent.Instance.build().inject(this);
MyPreferencesComponent.Instance.build().inject(this);
}
#Inject
public void setRestClient(RestClient restClient){
this.restClient = restClient;
}
#Inject
public void setSharedPreferences(SharedPreferences sharedPreferences){
this.sharedPreferences = sharedPreferences;
}
}
You don't need to create components for each module. You can just add more modules to component and as provide all classes in on this one interface.
#Singleton
#Component(
modules = {RestModule.class, PreferencesModule.class}
)
public interface AppComponent {
void inject(MainApplication app)
void inject(MainActivity activity);
}
if you are asking for inject component to all activites/fragment/MainApplication there is no method for this. You have to specify which of these above will get dependency injection.

Dagger can't inject a Presenter in my Activities

I'm refactoring an Android app to an MVP architecture, using Dagger 1.
My code is more or less the following:
public interface View {
Presenter getPresenter();
}
public abstract class Presenter {
// Dagger 1 can't have an abstract class without injectable members... :(
#Inject
Application dont_need_this;
protected View view;
public void takeView(View view) { ... }
}
The field in Presenter is not pretty, but what can we do?
Next, I have an Activity that's also a View.
public abstract class ActivityView extends Activity implements View {
#Inject
protected Presenter presenter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ObjectGraph scope;
// Looks for an "scoped" ObjectGraph hold in an retained fragment
if (/* fragment is null */) {
// This is not a rotation but the first time the activity is
// launched
MVPApplication app = (MVPApplication) getApplication();
ObjectGraph scope = app.createScope(this);
// Store in the fragment
}
scope.inject(this);
// setContentView, etc.
presenter.takeView(this);
}
}
All seems good for now...
public abstract class MVPApplication extends Application {
private ObjectGraph objectGraph;
#Override
public void onCreate() {
super.onCreate();
// Root scope
// createRootModules is defined in the subclass
objectGraph = ObjectGraph.create(createRootModules());
objectGraph.inject(this);
}
public abstract ObjectGraph createScope(View view);
}
With this, my application subclass has to:
define createRootModules() to instantiate every module in the root scope
check in createScope() the class of the concrete ActivityView, essentially using a HashMap<Class<? extends View>, Module> and do...
return objectGraph.plus(new ModuleForThisActivityViewClass());
For example, I have an CollectionActivityView. My app tries to...
return objectGraph.plus(new CollectionModule());
And I have the binding for this particular Presenter in this module:
#Module(addsTo = MyAppModule.class,
injects = {CollectionActivityView.class, CollectionPresenter.class}, complete=false)
public class CollectionModule {
#Provides
#Singleton
public Presenter providePresenter(CollectionPresenter presenter) {
return presenter;
}
}
But when doing the 'plus()` this error happens:
ComponentInfo{com.mycompany.myapp/com.mycompany.myapp.view.CollectionActivityView}:
java.lang.IllegalStateException: Unable to create binding for
com.mycompany.myapp.mvp.presenter.Presenter
...
Caused by: java.lang.IllegalStateException: Unable to create binding for
com.mycompany.myapp.mvp.presenter.Presenter
at dagger.internal.Linker.linkRequested(Linker.java:147)
at dagger.internal.Linker.linkAll(Linker.java:109)
at dagger.ObjectGraph$DaggerObjectGraph.linkEverything(ObjectGraph.java:244)
at dagger.ObjectGraph$DaggerObjectGraph.plus(ObjectGraph.java:203)
Dagger is trying to resolve the dangling dependency of the superclass Presenter in ActivityView before plusing the ObjectGraph with the new Module, who is in charge of providing the Presenter.
Is there a way to avoid this? Am I doing something terribly wrong? Do you have any suggestions for doing this properly?
Looking at it again, it was my fault.
I don't know why I did it (probably trying to avoid tagging the module as incomplete or library) but MyAppModule declared it was injecting CollectionActivityView, so the Presenter dependency had to be resolved in that module before plussing the other. Removed that from the annotation in MyAppModule and everything worked as intended.

Activity graphs and non-found dependency

I'm starting using the dagger, like it pretty much, but now facing some difficulties. My scenario is as follows: there's an activity and a dependency for it. Dependency is injected to the activity, and requires a reference to that activity. Just like this:
public class MainActivity extends BaseActivity {
#Inject ScbeHelper scbeHelper;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
...
}
}
public class ScbeHelper {
protected static final String TAG = "scbe_helper";
private BaseActivity activityContext;
#Inject
public ScbeHelper(BaseActivity context) {
this.activityContext = context;
}
}
I'm following dagger's example from the github for activity's graphs. So I've created a similar structure in my project. First, the BaseActivity class, from which MainActivity is inherited:
public abstract class BaseActivity extends Activity {
private ObjectGraph activityGraph;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
protoApp application = (protoApp) getApplication();
// Exception happens in next line, inside plus() method
activityGraph = application.getApplicationGraph().plus(getModules().toArray());
// Inject ourselves so subclasses will have dependencies fulfilled when this method returns.
activityGraph.inject(this);
((protoApp)getApplication()).inject(this);
}
protected List<Object> getModules() {
return Arrays.<Object>asList(new ActivityModule(this));
}
public void inject(Object object) {
activityGraph.inject(object);
}
}
And the module:
#Module(injects={MainActivity.class})
public class ActivityModule {
private final BaseActivity activity;
public ActivityModule(BaseActivity activity) {
this.activity = activity;
}
#Provides #Singleton BaseActivity provideActivity() {
return activity;
}
}
Now, the problem: No injectable members on com.example.proto.BaseActivity. Do you want to add an injectable constructor? required by public com.example.proto.ScbeHelper(com.example.proto.BaseActivity)
In other words, provider method ActivityModule.provideActivity() doesn't really provide the instance of BaseActivity for some reason, though in my understanding it's set up correctly. Does anyone see an error in my setup? Am I missing something in dagger's logic?
Thanks in advance!
I'm no Dagger expert, but you have 2 issues:
you have a cyclical dependency: you helper want to have the activity injected, your activity wants to have the helper injected. I don't think Dagger can resolve this
your activity tries to get injected twice, once with the activity-level graph, once with the application-level graph
Here's what I did to get it to work:
in ScbeHelper: remove the #Inject annotation
in BaseActivity: remove ((protoApp)getApplication()).inject(this);
in ActivityModule: remove your provideActivity method (it's not going to be used anymore), and add the following method:
#Provides #Singleton ScbeHelper provideScbeHelper() {
return new ScbeHelper(activity);
}
What this does is it provides your ScbeHelper with the context it needs, but leaves only 1 annotation-driven injection so dagger can resolve it. Hope this helps.

Categories

Resources