Java – dagger 2 has no initialization variables
•
Android
Now I'm trying to implement dagger in my project. I have a problem. Variables initialized in application components are not initialized in my activity. This is my code. Application:
public class MyApplication extends Application {
private ApplicationComponent applicationComponent;
@Inject
public Context context;
@Override
public void onCreate() {
super.onCreate();
applicationComponent = DaggerApplicationComponent.builder().applicationModule(new ApplicationModule(this)).build();
applicationComponent.inject(this);
}
public ApplicationComponent getApplicationComponent() {
return applicationComponent;
}
}
Here is the variable context= null
Activities:
public class MainActivity extends AppCompatActivity {
private ActivityComponent activityComponent;
@Inject
Context context;
@Override
protected void onStart() {
super.onStart();
activityComponent = DaggerActivityComponent.builder()
.activityModule(new ActivityModule(this))
.applicationComponent(((MyApplication) getApplication()).getApplicationComponent())
.build();
activityComponent.inject(this);
}
}
Here context = = null
Dagger:
@Component(modules = {ApplicationModule.class})
public interface ApplicationComponent {
void inject(MyApplication application);
Context getApplicationContext();
}
@Component(modules = {ActivityModule.class}, dependencies = {ApplicationComponent.class})
public interface ActivityComponent {
void inject(MainActivity mainActivity);
}
@Module
public class ApplicationModule {
private Application application;
public ApplicationModule(MyApplication application) {
this.application = application;
}
@Provides
Context provideApplicationContext() {
return application.getApplicationContext();
}
}
@Module
public class ActivityModule {
Activity activity;
public ActivityModule(MainActivity activity) {
this.activity = activity;
}
}
Therefore, dagger only provides "context" in the application class, but not in the mainactivity class. What did I do wrong? Maybe I want to change something
thank you!
resolvent:
The settings are as follows:
public class MyApplication extends Application {
private ApplicationComponent applicationComponent;
@Override
public void onCreate() {
super.onCreate();
applicationComponent = DaggerApplicationComponent.builder()
.applicationModule(new ApplicationModule(this))
.build();
}
public ApplicationComponent getApplicationComponent() {
return applicationComponent;
}
}
And your activities:
public class MainActivity extends AppCompatActivity {
@Inject
Context context;
@Override
protected void onStart() {
super.onStart();
((MyApplication) getApplication()).getApplicationComponent().inject(this);
}
}
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码