Injecting Context in MVP Presenter Android [duplicate] - java

This question already has an answer here:
How do I fix Dagger 2 error '... cannot be provided [...]'?
(1 answer)
Closed 5 years ago.
I am using MVP Architecture along with Dagger2. I want to get Context in my Presenter using constructor injection.
My Activity :
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_appintroduction);
activityComponent().inject(this);
ButterKnife.bind(this);
skipall.bringToFront();
}
My Presenter:
#ConfigPersistent
public class AppIntroPresenter extends BasePresenter<AppIntroMvpView> {
private final DataManager mDataManager;
private final Context ctx1;
#Inject
public AppIntroPresenter(DataManager dataManager,Context context) {
mDataManager = dataManager;
ctx1=context;
}
public void openCamView(Context ctx) {
ctx.startActivity(new Intent(ctx, CameraActivity.class));
}
}
My Application Component :
#Singleton
#Component(modules = ApplicationModule.class)
public interface ApplicationComponent {
void inject(SyncService syncService);
#ApplicationContext Context context();
Application application();
RibotsService ribotsService();
PreferencesHelper preferencesHelper();
DatabaseHelper databaseHelper();
DataManager dataManager();
RxEventBus eventBus();
ClassService classService();
AnsweredQuestionService answeredQuestionService();
}
My Activity Component:
#PerActivity
#Subcomponent(modules = ActivityModule.class)
public interface ActivityComponent {
void inject(MainActivity mainActivity);
void inject(CameraActivity cameraActivity);
void inject(AppIntroActivity appIntroActivity);
}
My Application Module:
#Module
public class ApplicationModule {
protected final Application mApplication;
public ApplicationModule(Application application) {
mApplication = application;
}
#Provides
Application provideApplication() {
return mApplication;
}
#Provides
#ApplicationContext
Context provideContext() {
return mApplication;
}
#Provides
#Singleton
RibotsService provideRibotsService() {
return RibotsService.Creator.newRibotsService();
}
#Provides
#Singleton
ClassService provideClassService() {
return ClassService.Creator.newClassService();
}
#Provides
#Singleton
AnsweredQuestionService provideAnsweredQuestionService() {
return AnsweredQuestionService.Creator.newAnsweredQuestionService();
}
}
My Activity Module:
#Module
public class ActivityModule {
private Activity mActivity;
public ActivityModule(Activity activity) {
mActivity = activity;
}
#Provides
Activity provideActivity() {
return mActivity;
}
}
After running the code, i get error:
Error:(17, 8) error: [uk.co.ribot.androidboilerplate.injection.component.ActivityComponent.inject(uk.co.ribot.androidboilerplate.ui.AppIntro.AppIntroActivity)] android.content.Context cannot be provided without an #Provides-annotated method.
android.content.Context is injected at
uk.co.ribot.androidboilerplate.ui.AppIntro.AppIntroPresenter.<init>(…, context)
uk.co.ribot.androidboilerplate.ui.AppIntro.AppIntroPresenter is injected at
uk.co.ribot.androidboilerplate.ui.AppIntro.AppIntroActivity.mAppIntroPresenter
uk.co.ribot.androidboilerplate.ui.AppIntro.AppIntroActivity is injected at
uk.co.ribot.androidboilerplate.injection.component.ActivityComponent.inject(appIntroActivity)
I know when i add context to constructor injection in My Presenter i get this error, but i am not able to figure out why? If i remove the context from constructor :
#Inject
public AppIntroPresenter(DataManager dataManager,Context context) {
mDataManager = dataManager;
ctx1=context;
}
Then everything works fine. But i need the context from injection. Please help me with this?

Since your constructor has members, you need to create a module and create there an instance annotated with #Provides and #Singleton, same as ApplicationModule.

Related

Dagger singleton creating new instance every time

I have a module as follows.
#Module
public class AppModule {
private final Application app;
public AppModule(Application app) {
this.app = app;
}
#Provides
#Architecture.ApplicationContext
Context provideContext() {
return app;
}
#Provides //scope is not necessary for parameters stored within the module
public Context context() {
return provideContext();
}
#Singleton
#Provides
Application provideApp() {
return app;
}
#Singleton
#Provides
SoundsRepository provideSoundsRepository(Context context, SoundsDAO soundsDAO) {
return new SoundsRepository(context, soundsDAO);
}
}
A component like this.
#Singleton
#Component(modules = AppModule.class)
public interface AppComponent {
void inject(Global global);
void inject(MainActivity mainActivity);
#Architecture.ApplicationContext
Context getContext();
Application getApplication();
void inject(PostView postView);
void inject(MediaPlayerService mediaPlayerService);
}
In activity, fragment or service, I do this
#Inject
SoundsRepository soundsRepository;
#Override
protected void onCreate(...) {
//....
((Global) getApplication()).getComponent().inject(this);
}
In SoundsRepository
#Singleton
public class SoundsRepository {
#Inject
public SoundsRepository(Context context, SoundsDAO soundsDAO) {
this.context = context;
this.soundsDAO = soundsDAO;
System.out.println(TAG + "INIT");
}
// ....
}
So, now, every time I start to access an activity or service where SoundsRepository is injected, I get a new instance, I mean, the constructor of "SoundsRepository" fires again.
What am I doing wrong?
EDIT : Inject in Application Class
public class Global extends MultiDexApplication {
protected AppComponent appComponent;
private boolean calledAlready = false;
#Override
public void onCreate() {
super.onCreate();
//if (LeakCanary.isInAnalyzerProcess(this)) return;
//LeakCanary.install(this);
initFirebasePersistance();
appComponent = DaggerAppComponent.builder().appModule(new AppModule(this)).build();
appComponent.inject(this);
FrescoUtil.init(getApplicationContext());
}
public AppComponent getComponent() {
return appComponent;
}
}
In your module you have a method that provides an instance of SoundsRepository - good
In your AppComponent you are missing a:
SoundsRepository soundsRepository();
In your Global which extends Application/MultidexApplication you create your DaggerAppComponent - good
In your other activities/fragments/services just call:
Global application = (Global) getApplication();
SoundsRepository sr = application.getComponent().soundsRepository()
Android guarantees you have only one instance of your Application (Global) class for all other actvities/services (its somewhat like a singleton).
So keep your component in that application class, and whenever you need your class, call: (YourApplication) getApplication().getComponent().yourSingleInstanceSomething();
I created and tested sample code for you: https://github.com/zakrzak/StackDaggerTest
Dagger's #Singleton is just a scope, and does not guarantee returning a singular instance of a class.
In my understanding, if you:
void inject(PostView postView);
you tell Dagger to make everything you annotated with #Provided in AppModule accessible in your PostView as soon as you request it with:
#Inject
SoundsRepository soundsRepository;
then dagger just calls the #provided method which in your case returns a new SoundRepository instance:
#Singleton
#Provides
SoundsRepository provideSoundsRepository(Context ........) {
return new SoundsRepository(...);
}
which causes your problem

What's is wrong with this dagger2 simple example?

1 - Scope:
#Scope
#Retention(RetentionPolicy.CLASS)
public #interface PerInstance {}
2 - AppContextModule:
#Module
public class AppContextModule {
Application application;
public AppContextModule(Application application){
this.application = application;
}
#Provides
public Application application(){
return this.application;
}
#Provides
public Context context(){
return this.application;
}
#Provides
public LocationManager locationManager(Context context){
return (LocationManager) context.getSystemService(context.LOCATION_SERVICE);
}
}
3 - MeuPrimeiroModule:
#Module
public class MeuPrimeiroModule {
#Provides
#PerInstance
public String nome() {
return new String("Gorick");
}
}
4 - MeuSegundoModule:
#Module(includes = MeuPrimeiroModule.class)
public class MeuSegundoModule {
#Provides
#Singleton
public String nomeCompleto(MeuPrimeiroModule meuPrimeiroModule) {
return new String(meuPrimeiroModule + " Silva");
}
}
5 - MeuPrimeiroComponent:
#PerInstance
#Component(modules={MeuPrimeiroModule.class})
public interface MeuPrimeiroComponent {
void inject(MainActivity mainActivity);
}
6 - MeuSegundoComponent:
#Singleton
#Component(modules={MeuSegundoComponent.class})
public interface MeuSegundoComponent extends MeuPrimeiroComponent {
void inject(MainActivity mainActivity);
}
7 - AppContextComponent:
public interface AppContextComponent {
Application app(); //provision method
Context applicationContext(); //provision method
LocationManager locationManager(); //provision method
}
8 - ApplicationComponent:
#Singleton
#Component(modules={AppContextModule.class})
public interface ApplicationComponent extends AppContextComponent {
void inject(MainActivity mainActivity);
}
9 - MainActivity:
public class MainActivity extends AppCompatActivity {
#Inject
MeuPrimeiroComponent meuPrimeiroComponent;
#Inject
MeuSegundoComponent meuSegundoComponent;
TextView nome, nomeCompleto;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
nome = (TextView) findViewById(R.id.nome);
nomeCompleto = (TextView) findViewById(R.id.nomeCompleto);
setNome(nome, nomeCompleto);
}
public void setNome(TextView nome, TextView nomeCompleto){
nome.setText(meuPrimeiroComponent.toString());
nomeCompleto.setText(meuSegundoComponent.toString());
}
}
Build:
Error:(16, 10) error: gorick.dagger2.Dagger2.Component.MeuPrimeiroComponent cannot be provided without an #Provides- or #Produces-annotated method.
gorick.dagger2.Dagger2.Component.MeuPrimeiroComponent is injected at
gorick.dagger2.MainActivity.meuPrimeiroComponent
gorick.dagger2.MainActivity is injected at
gorick.dagger2.Dagger2.Component.ApplicationComponent.inject(mainActivity)
PS: If i use meuPrimeiroComponent.nome(), android studio doesn't find the nome() method.
You cannot inject values in component instead you need to inject in object whose constructor contains values which is returns by the providers
For more info Ref this Example
You need build Component like this on onCreate():
DaggerMeuPrimeiroComponent.builder()
// list of modules that are part of this component need to be created here too
.appContextModule(new AppContextModule(getApplicationContext())) // This also corresponds to the name of your module: %component_name%Module
.build().inject(this);

Android use dependency injection for simple custom class

after search on web for learning about this feature most topics or post was using dependency injection for Retrofit or other android useful libraries, but i have some custom class which i want to use that with DI and i can't done it, for example i have simple custom class for using SharePreference and i'm using with that as an Singleton class
in my code i can't assign correct Dagger to component on SpApplication class to use that on activities or fragments
public class SP {
private SharedPreferences preferences;
private Context context;
public SP(Context context) {
this.context = context;
}
private SharedPreferences getPrefs() {
return preferences = PreferenceManager.getDefaultSharedPreferences(context);
}
public String getString(SharedPrefsTypes propertyName) {
return getPrefs().getString(propertyName.toString(), "");
}
public int getInt(SharedPrefsTypes propertyName) {
return getPrefs().getInt(propertyName.toString(), 0);
}
...
public enum SharedPrefsTypes {
Login
}
}
now i'm trying to use DI for that:
AppModules class:
#Module
public class AppModules {
private Context context;
public AppModules(Context context) {
this.context = context;
}
#Provides
#Singleton
SP provideSharePreferences() {
SP sharePreference = new SP(context);
return sharePreference;
}
}
ApplicationComponent class:
#Component(modules = AppModules.class)
public interface ApplicationComponent {
void inject(ActivityMain activity);
}
SpApplication class:
public class SpApplication extends Application {
private static SpApplication self;
private ApplicationComponent component;
#Override
public void onCreate() {
super.onCreate();
self = this;
component = DaggerApplicationComponent.builder().build();
}
public static SpApplication get(Context context) {
return (SpApplication) context.getApplicationContext();
}
public static SpApplication getInstance() {
return self;
}
public ApplicationComponent getComponent() {
return component;
}
}
and my ActivityMain class:
public class ActivityMain extends AppCompatActivity {
#Inject
SP sharePreference;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
((SpApplication) getApplication()).getComponent().inject(this);
sharePreference.setInt(SP.SharedPrefsTypes.Login, 0);
}
}
I get this error:
android.app.Application cannot be cast to com.pishguy.yendir.SpApplication
Thanks in advance
I guess you are trying to inject into ActivityMain, but since you did not provide its source, let me show you how you could inject into SpApplication. Then just copy the relevant parts into your Activity.
Few things I think you need to change.
Module:
Your AppModules class is generally OK, but I just suggest you to change the way you make use of Context - don't use it as a field, but inject it as any other service. It looks like this:
#Module
public class AppModules {
private Context context;
public AppModules(Context context) {
this.context = context;
}
#Provides // this can be non-scoped because anyway the same instance is always returned
Context provideContext() {
return this.context;
}
#Provides
#Singleton
SP provideSharePreferences(Context context) {
return new SP(context); // use method-local Context
}
}
Component:
If component injects scoped services (#Singleton is a scope), the component itself must be scoped
If you want to inject into SpApplication class, then declare it as an injection client in the component
Taking into account these two points, ApplicationComponent should look like this:
#Singleton // injects #Singleton scoped services
#Component(modules = AppModules.class)
public interface ApplicationComponent {
void inject(SpApplication application); // SpApplication is DI client (injection target)
}
Client:
I'd change few things in your SpApplication class:
The way you instantiate ApplicationComponent is incorrect
This is not a bug, but you don't really need get(Context) and getInstance() methods
In addition, since I'm showing how you inject into SpApplication, I will add the injection logic as well (which you should copy to your actual clients).
So, SpApplication (which is DI client) should look similar to this:
public class SpApplication extends Application {
#Inject SP sp; // the dependency that should be injected
private ApplicationComponent component;
#Override
public void onCreate() {
super.onCreate();
getComponent().inject(this); // this is when the actual injection takes place
}
public ApplicationComponent getComponent() {
if (component == null) {
// this is the way Dagger components should be instantiated
component = DaggerApplicationComponent.builder()
.appModules(new AppModules(this))
.build();
}
return component;
}
}
If you perform the above changes, I tend to believe that you'll be all right.
BTW, I recently completed a blog post about Dagger 2 scopes. You might want to check it if you are going to be serious about dependency injection.

Dagger2 module: how to obtain context to pass to the constructor of a class I want to provide

First time using Dagger2.
In my android application I have a MyApplication class that extends Application.
I also have an ImageAssistant class that is a collection of related image-processing methods.
In my MyApplicaiton class I used to instantiate an ImageAssistant for all the activities to use.
Now I am trying to make it work with Dagger2, but I dont know how to pass a context in the module that provides ImageAssistant
This is how my code looked:
public class ImageAssistant {
Context context;
public ImageAssistant(Context context){
this.context = context;
}
// A bunch of methods...
}
public class MyApplication extends Application {
public ImageAssistant imageAssistant;
public void onCreate() {
imageAssistant = new ImageAssistant(this);
}
}
Now, enter Dagger 2, here is what I have
public class ImageAssistant {
Context context;
#Inject
public ImageAssistant(Context context){
this.context = context;
}
// A bunch of methods...
}
public class MyApplication extends Application {
#Inject
public ImageAssistant imageAssistant;
public void onCreate() {
}
}
in package .modules:
AppModule.java
#Module
public class AppModule {
#Provides
ImageAssistant provideImageAssistant() {
return new ImageAssistant(); // HERE A CONTEXT IS NEEDED. WHERE TO GET IT FROM?
}
}
EDIT: This is how my module looks now, but I still dont know how to tie everything together:
#Module
public class AppModule {
private MyApplication application;
public AppModule(MyApplication application) {
this.application = application;
}
#Provides
Context provideApplicationContext() {
return this.application;
}
#Provides
ImageAssistant provideImageAssistant(ImageAssistant imageAssistant) {
return imageAssistant;
}
}
And this is the AppComponent:
#Singleton
#Component(modules = {AppModule.class})
public interface AppComponent {
ImageAssistant provideImageAssistant();
Context context();
}
Your module should look like this:
#Module(injects = {MainActivity.class})
public class AppModule {
private MyApplication application;
public AppModule(MyApplication application) {
this.application = application;
}
#Provides
public ImageAssistant provideImageAssistant() {
return new ImageAssistantImpl(application); // implementation of ImageAssistant
}
}
Usage in Activity:
public class MainActivity extends Activity{
#Inject
ImageAssistant imageAssistant;
#Override
protected void onCreate(Bundle savedInstanceState) {
SharedObjectGraph.inject(this);
imageAssistant.doSomething();
}
}
Don't forget to init the ObjectGraph in Application class. I use SharedObjectGraph static class to share ObjectGraph created from AppModule across the whole app.
Read building the graph section.
I did something like this:
#Module
public class ApplicationModule {
private final SpendApplication app;
public ApplicationModule(SpendApplication app) {
this.app = app;
}
#Provides
#Singleton
public Context providesContext() {
return app;
}
}
and:
#Module
public class GattManagerModule {
#Provides
#Singleton
GattManager providesGattManager(Context context) {
return new GattManager(context);
}
}
And declare all places where it's used:
#Component(modules = { ApplicationModule.class, GattManagerModule.class, ...})
#Singleton
public interface ApplicationComponent {
void inject(MainScreenActivity activity);
...
}
In my app application class:
#Override
public void onCreate() {
super.onCreate();
component = DaggerApplicationComponent.builder()
.applicationModule(new ApplicationModule(this))
.build();
}
And in my MainActivity:
#Inject
GattManager gattManager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getAppComponent().inject(this);
}

Injecting field into module using dagger

I am trying to inject my android context from one module into another. This is my code so far:
UserProfileModule.java
#Module(
library = true
)
public class UserProfileModule {
#Inject Context _context;
#Provides
public AccountUtils.UserProfile provideUserProfile() {
return AccountUtils.getUserProfile(_context);
}
}
RootModule.java
#Module(
injects = {
PizzaApplication.class,
UserProfileModule.class,
MainActivity.class
},
includes = {
UserProfileModule.class
},
library = true
)
public class RootModule {
private final Context _context;
public RootModule(Context context) {
_context = context;
}
#Provides
#Singleton
public Context provideApplicationContext() {
return _context;
}
}
Anytime it tries to get the user profile it fails saying the object is null.]
EDIT:
PizzaApplication.java
public class PizzaApplication extends Application {
private ObjectGraph objectGraph;
#Override
public void onCreate() {
super.onCreate();
injectDependencies();
}
private void injectDependencies() {
objectGraph = ObjectGraph.create(new RootModule(this));
objectGraph.inject(this);
}
public void inject(Object object) {
objectGraph.inject(object);
}
}
MainActivity.java
public class MainActivity extends BaseActivity {
#InjectView(R.id.toolbar) public Toolbar _toolbar;
#InjectView(R.id.drawer) public DrawerFrameLayout _drawer;
#Inject public AccountUtils.UserProfile _profile;
#Inject public Context _context;
// private NavigationDrawerFragment navigationDrawerFragment;
#Override
protected void onCreate(Bundle saveInstanceState) {
tl;dr (Short version):
For a minimal working example of your code, see my code on GitHub
You don't need to / should't inject the Context from one module into another.
The order/direction of your module includes is reversed, the UserProfileModule should include the RootModule.
More details and comments on your code:
You don't need to inject something into a module, a module only provides dependencies. In your case simply making use of the module includes gives the functionality you want.
Remove the library = true from UserProfileModule, because you only need this when the module's providers aren't all used directly by the classes specified in the injects list.
As Niek Haarman said, you need to pass both RootModule and UserProfileModule instances to ObjectGraph.create in your PizzaApplication's onCreate.
You're doing inject(this) in PizzaApplication but it's got no dependencies, so the inject isn't necessary. Based on the sample code you've provided, this makes me think you're assuming that injecting on the Application-level will also inject Activity dependencies...? You need to do the inject on your Activity too.
You don't show if you're doing an inject in your Activity's onCreate -- that's most likely what's missing.
You're injecting Context into the Activity but that's not necessary since you can just use getApplicationContext() in the Activity.
Here's the working code:
RootModule:
#Module(
injects = {MainActivity.class},
library = true,
complete = false
)
public class RootModule {
private final Context _context;
public RootModule(Context context) {
_context = context;
}
#Provides
#Singleton
public Context provideApplicationContext() {
return _context;
}
}
UserProfileModule:
#Module(includes = {RootModule.class})
public class UserProfileModule {
#Provides
public AccountUtils.UserProfile provideUserProfile(Context context) {
return AccountUtils.getUserProfile(context);
}
}
MainActivity:
public class MainActivity extends BaseActivity {
#Inject
public AccountUtils.UserProfile _profile;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
((PizzaApplication) getApplication()).inject(this);
_profile.message();
}
PizzaApplication:
public class PizzaApplication extends Application {
private ObjectGraph objectGraph;
#Override
public void onCreate() {
super.onCreate();
objectGraph = ObjectGraph.create(new RootModule(this), new UserProfileModule());
}
public void inject(Object object) {
objectGraph.inject(object);
}
}
You have
objectGraph = ObjectGraph.create(new RootModule(this));
But, includes = { UserProfileModule.class } is no magic. You have to create it yourself:
objectGraph = ObjectGraph.create(new RootModule(this), new UserProfileModule() );
Furthermore, the #Inject annotation on the Context doesn't work. You're better off modifying your provider method:
#Provides
public AccountUtils.UserProfile provideUserProfile(Context context) {
return AccountUtils.getUserProfile(context);
}
I cannot guarantee this will solve all your problems, but it will help you in the right direction.

Categories

Resources