I'm new to Dagger2 and I'm trying to use dependency injection in my application.
I'm using shared preferences and thought it will be more helpful to use dependency injection instead of getting an instance of shared prefrences each time I need to use it.
It works fine when I'm using it on activities and fragments but when I'm trying to use it on service or intentservice it doesn't work.
Here is my code:
AppModule:
#Module
public class AppModule
{
public final ApplicationClass application;
public AppModule(ApplicationClass application)
{
this.application = application;
}
#Provides #Singleton
Context providesApplicationContext()
{
return this.application;
}
#Provides #Singleton
SharedPreferences providesSharedPreferences()
{
return application.getSharedPreferences(Constants.FILE_NAME,Context.MODE_PRIVATE);
}
}
AppComponent
#Singleton #Component(modules = {AppModule.class})
public interface AppComponent
{
void inject (ApplicationClass applicationClass);
void inject (IntentService intentService);
void inject (Service service);
}
ApplicationClass
public class ApplicationClass extends Application
{
AppComponent appComponent;
#Override
public void onCreate()
{
super.onCreate();
Thread.setDefaultUncaughtExceptionHandler(new
Thread.UncaughtExceptionHandler() {
#Override
public void uncaughtException(Thread t, Throwable e) {
onUncaughtException(t, e);
}
});
appComponent = DaggerAppComponent
.builder()
.appModule(new AppModule(this))
.build();
appComponent.inject(this);
}
public AppComponent getAppComponent()
{
return this.appComponent;
}
private void onUncaughtException(Thread t, Throwable e)
{
e.printStackTrace();
Intent crash= new Intent(getApplicationContext(),Crash.class);
about.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(crash);
}
}
So I tried to inject the shared preferences in IntentService and I used these lines of code
inside the onCreate method of the my service (intentservice)
#Inject
SharedPreferences preferences;
#Override
public void onCreate()
{
super.onCreate();
((ApplicationClass)getApplication()).getAppComponent().inject(this);
}
But the problem is when I use this preferences variable in the onHandleIntent method, the application is crashing because the preferences is null..
So why it doesn't inject?
For anyone who encountered this problem.
As Vadim Korzun and EpicPandaForce mentioned in their comments above,
I should specify the specific class in the inject method.
So in my case my IntentService class was named GeofenceService
and inside the AppComponent interface I should write
void inject (GeofenceService service);
Same thing for Service
UPDATE:
So for all the people who have multiple Services that inherit from IntentService and want to save themselves from writing inject method for each Specific service.
I would suggest to do the steps below:
Create BasicIntentService that extends IntentService
In your AppComponent interface add the inject method which take as parameter you BasicIntentService.
In your BasicIntentSerive, you will have a protected SharedPrefrences variable annotated with the Inject annotation.
Still, in your BasicIntentService, inside the onCreate method you will call this line of code
((ApplicationClass)getApplication()).getAppComponent().inject(this);
Now each IntentService that you will create will extends the BasicIntentService and you will be able to use the SharedPreferences variable.
AppComponent:
#Singleton #Component(modules = {AppModule.class})
public interface AppComponent
{
void inject (YourApplicationClass applicationClass);
void inject (BasicIntentService intentService);
}
BasicIntentService
public class BasicIntentService extends IntentService
{
#Inject
protected SharedPreferences sharedPreferences;
#Override
public void onCreate()
{
super.onCreate()
((YourApplicationClass)getApplication()).getAppComponenet().inject(this);
}
}
SomeIntentService
public class SomeIntentService extends BasicIntentService
{
#Override
public void onCreate()
{
super.onCreate();
}
-----------
#Override
protected void onHandleIntent(#Nullable Intent intent)
{
// some code
if (sharedPreferences.contains(someKey))
{
// some code
}
else
{
// some code
}
}
}
Related
I am trying to make an injection using Dagger 2, but it always returns null. I think I am doing all right, but anyway it does not work.
Here is the application class:
public class ApplicationSA extends Application {
private static AppComponent appComponent;
#Override
public void onCreate() {
super.onCreate();
appComponent = DaggerAppComponent.create();
}
public static AppComponent getComponent() {
return appComponent;
}
}
The component interface:
#Component(modules = {
SnoreDetectorClass.class,
AudioRecorderClass.class
})
public interface AppComponent {
void injectsMainFunctionalityActivity(Activity activity);
}
An the main class where I am trying to get the object:
public class MainFunctionalityActivity extends AppCompatActivity {
#Inject
AudioRecorderClass audioRecorderClass;
#Inject
SnoreDetectorClass snoreDetectorClass;
#Override
protected void onCreate(Bundle savedInstanceState) {
ApplicationSA.getComponent().injectsMainFunctionalityActivity(this);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.d("TESTING","audioRecorderClass= "+audioRecorderClass); // always null
Log.d("TESTING","snoreDetectorClass= "+snoreDetectorClass); // always null
...
}
And here are the module classes:
#Module
public class AudioRecorderClass {
public interface AudioRecorderInterface {
void AudioRecorder_hasUpdate(double amplitude_in_dB);
}
public AudioRecorderInterface delegate = null;
#Provides
AudioRecorderClass provideAudioRecorderClass(Activity activity) {
delegate = (AudioRecorderInterface)activity;
return new AudioRecorderClass();
}
...
#Module
public class SnoreDetectorClass {
#Provides
SnoreDetectorClass provideSnoreDetectorClass() {
return new SnoreDetectorClass();
}
...
What am I doing wrong ? Why the objects are always null ?
Ah, I see what is going on here. You cannot inject into a subclass. So in your AppComponent you cannot have
void injectsMainFunctionalityActivity(Activity activity);
you must inject with
void injectsMainFunctionalityActivity(MainFunctionalityActivity activity);
As a side note I would suggest not combining your injector and your model class. Better to have separation of concerns. Keep them separate
You have to specifically tell dagger which activity will be injected here, not use the super class Activity but rather your own implementation of the Activity class :
void injectsMainFunctionalityActivity(Activity activity);
change to:
void injectsMainFunctionalityActivity(MainFunctionalityActivity activity);
I am using MVP pattern with a Fragment(GalleryFragment), where Application class(MainApplication) sources MainActivityRepository and GalleryFragmentPresenter(grouped as DIModules) which are provided to Fragment through field injection.
To test GalleryFragment in isolation, my idea was to use Robolectric configuration(#Config) to replace MainApplication entirely with a custom TestApplication sourcing mockDIModules.
GalleryFragmentTest runs until startFragment(galleryFragment) but I get a NullPointerException at MainApplication.getComponent().inject(this); inside GalleryFragment.
I suspect this is because this line specifically uses MainApplication while everything else is dealt with TestApplication set by Robolectric #Config, but I'm not sure and I am looking for advice on how to successfully run tests using this custom TestApplication.
While searching for possible solutions, I found out about using AndroidInjector from Dagger support library, which will get rid of MainApplication.getComponent().inject(this); entirely but would this work?
https://android.jlelse.eu/android-and-dagger-2-10-androidinjector-5e9c523679a3
GalleryFragment.java
public class GalleryFragment extends Fragment {
#Inject
public MainActivityRepository mRepository;
#Inject
public GalleryFragmentPresenter mGalleryFragmentPresenter;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
MainApplication.getComponent().inject(this); //NullPointerException here
mGalleryFragmentPresenter.initialize(mRepository, value);
}
}
DIModules.java
#Module
public class DIModules {
#Provides
public GalleryFragmentPresenter provideGalleryFragmentPresenter(){
return new GalleryFragmentPresenter();
}
#Provides
#Singleton
public MainActivityRepository provideMainActivityRepository(){
return new MainActivityRepository();
}
}
AppComponent.java
#Singleton
#Component(modules = DIModules.class)
public interface AppComponent {
void inject(GalleryFragment galleryFragment);
}
MainApplication.java
public class MainApplication extends Application {
public static AppComponent component;
#Override
public void onCreate() {
super.onCreate();
Realm.init(this);
component = buildComponent();
}
public static AppComponent getComponent() {
return component;
}
protected AppComponent buildComponent(){
return DaggerAppComponent
.builder()
.dIModules(new DIModules())
.build();
}
}
TestApplication.java
public class TestApplication extends Application {
public static AppComponent component;
#Override
public void onCreate() {
super.onCreate();
component = buildComponent();
}
public static AppComponent getComponent() {
return component;
}
protected AppComponent buildComponent(){
return DaggerAppComponent.builder()
.dIModules(new mockDIModules())
.build();
}
}
GalleryFragmentTest.java
#RunWith(RobolectricTestRunner.class)
#Config(constants = BuildConfig.class,
application = TestApplication.class)
public class GalleryFragmentTest {
#Test
public void allItemTabTest() throws Exception {
GalleryFragment galleryFragment = GalleryFragment.newInstance(value);
startFragment(galleryFragment);
assertNotNull(galleryFragment);
}
}
I am using dagger, dagger-android-support, dagger-compiler version 2.14.1 and robolectric:3.6.1
Of course, it is null. Your fragment still tries to work with production application while you're doing things in the test application.
Change your injection code to next:
((MainApplication) getContext().getApplicationContext()).getComponent().inject(this);
And also make the method in your Application getComponent() as not static, so test app overrides it.
Another option is to change your TestApplication to next:
public class TestApplication extends Application {
#Override
public void onCreate() {
super.onCreate();
buildComponent();
}
private void buildComponent(){
Application.component = DaggerAppComponent.builder()
.dIModules(new mockDIModules())
.build();
}
}
I'm trying to understand Dagger2. I've followed a few examples and using one component/module makes sense but adding a second confuses me. Am I not able to use more than one component in my application class?
Both Dagger components are highlighted red and say "Cannot resolve symbol..."
public class MyApplication extends Application {
StorageComponent component;
ImageDownloaderComponent imageDownloaderComponent;
#Override
public void onCreate() {
super.onCreate();
component = DaggerStorageComponent
.builder()
.storageModule(new StorageModule(this))
.build();
imageDownloaderComponent = DaggerImageDownloaderComponent
.builder()
.imageDownloaderModule(new ImageDownloaderModule(this))
.build();
}
public StorageComponent getComponent() {
return component;
}
public ImageDownloaderComponent getImageDownloaderComponent() {
return this.imageDownloaderComponent;
}
}
I ended up putting both pieces (SharedPrefs and Picasso) in one module and returned the component in my application class. Hope the wording makes sense.
#Module
public class StorageModule {
private final MyApplication application;
public StorageModule(MyApplication application) {
this.application = application;
}
#Singleton
#Provides
SharedPreferences provideSharedPreferences() {
return PreferenceManager.getDefaultSharedPreferences(application);
}
#Singleton
#Provides
ImageDownloader provideImageDownloader() {
return new ImageDownloader(application);
}
}
MyApplication class:
public class MyApplication extends Application {
StorageComponent component;
#Override
public void onCreate() {
super.onCreate();
component = DaggerStorageComponent
.builder()
.storageModule(new StorageModule(this))
.build();
}
public StorageComponent getComponent() {
return component;
}
}
I have a class that's being injected using DI via dagger. However when the activity is destroyed and recreated, the model class seems to contain the data automatically without me insert/repopulating the data.
public class MyApplication extends Application {
private ExpressionFactoryComponent mExpressionFactoryComponent;
#Override
public void onCreate() {
super.onCreate();
// Building dagger DI component
mExpressionFactoryComponent = DaggerExpressionFactoryComponent.builder().
expressionFactoryModule(new ExpressionFactoryModule(new ExpressionFactory(this))).build();
}
}
Module:
#Module
public class ExpressionFactoryModule {
private ExpressionFactory mExpressionFactory;
public ExpressionFactoryModule(ExpressionFactory expressionFactory) {
this.mExpressionFactory = expressionFactory;
}
#Provides
ExpressionFactory provideStringExpressionFactory() {
return mExpressionFactory;
}
}
The one reason for this is that ExpressionFactory is instantiated in MyApplication class and then passed into the constructor of ExpressionFactoryModule while creating ExpressionFactoryComponent. You should pass an Application instance in your module constructor and then create an instance of your class withing a metod with #Provide annotation passing that Application instance in your class's constructor.
This how things should be done with dagger. But to solve your problem you need to create another component class and build the component in an activity if you need to have an instance of your class living withing an activity only.
Here is the solution (ExpressionFactoryComponent is renamed to AppComponent here):
public class MyApplication extends Application {
private static AppComponent appComponent;
#Override
public void onCreate() {
super.onCreate();
// Building dagger DI component
appComponent = DaggerAppComponent.builder()
.appModule(new AppModule(this)).build();
}
public static AppComponent getAppComponent() {
return appComponent;
}
}
#Component(modules = {AppModule.class})
public interface AppComponent {
Application getApplication();
void inject(App application);
}
#Module
public class AppModule {
private Application application;
public AppModule(Application application) {
this.application = application;
}
#Provides
Application provideApplication() {
return application;
}
}
#Component(dependencies = AppComponent.class, modules = {
ActivityModule.class})
public interface ActivityComponent {
void inject(MainActivity activity);
}
#Module
public class ActivityModule {
private Activity activity;
public ActivityModule(Activity activity) {
this.activity = activity;
}
#Provides
Activity provideActivity() {
return activity;
}
#Provides
ExpressionFactory provideStringExpressionFactory(Application application) {
return new ExpressionFactory(application);
}
}
public class MainActivity extends AppCompatActivity{
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ActivityComponent activityComponent = DaggerActivityComponent.builder()
.activityModule(new ActivityModule(activity))
.appComponent(App.getAppComponent())
.build();
activityComponent.inject(this);
}
}
I have an app which is basically a service that runs all the time and alarms the user when something happens.
When the service creates the alarm, it needs to give it his context so that the alarm can do callbacks to the service when something happens.
For example:
public MyService extends Service{
private SomeAlarm alarm;
#Override
public void onCreate() {
super.onCreate();
alarm = new SomeAlarm(MyService.this);
}
}
How can I inject the SomeAlarm class into the service, and give the SomeAlarm the service context as a variable?
I wrote the code from the top of my head, so there could be a typo or two.
You do it just the same as when injecting stuff into activities.
Declare a component,
add the inject method to that component,
add a module providing your service
create that components builder
add your module to the builder
inject your service with the component
Your module and component would look something like this (maybe add some scope)
#Module
class ServiceModule {
MyService mService;
ServiceModule(MyService service) {
mService = service;
}
#Provides
MyService provideMyService() {
return mService;
}
}
#Component(modules=ServiceModule.class)
interface MyServiceComponent {
void inject(MyService service);
}
Then in onCreate just create your component and inject your alarm.
#Inject
private SomeAlarm alarm;
public void onCreate() {
DaggerMyServiceComponent.builder()
.serviceModule(new ServiceModule(this))
.build()
.inject(this);
alarm.doStuff();
}
This is assuming that your alarm can be constructor injected by having an #Inject annotated constructor like this:
class SomeAlarm {
#Inject
SomeAlarm(MyService service) {
/*constructor stuff*/
}
}
Else you would just also add the alarm creation to your module.
I know this question already has an answer but there are an other way to do this
first make your application extend HasServiceInjector like this:
public class App extends Application implements HasActivityInjector,
HasServiceInjector {
#Inject
DispatchingAndroidInjector<Activity> dispatchingActivityInjector;
#Inject
DispatchingAndroidInjector<Service> dispatchingServiceInjector;
#Override
public void onCreate() {
super.onCreate();
AppInjector.init(this);
}
#Override
public AndroidInjector<Activity> activityInjector() {
return dispatchingActivityInjector;
}
#Override
public AndroidInjector<Service> serviceInjector() {
return dispatchingServiceInjector;
}
}
then create a ServiceBuilderModule this will perform injection over services:
#Module
abstract class ServiceBuilderModule {
#ContributesAndroidInjector
abstract MyService contributeMyService();
}
then register the new module to your component
#Component(modules = {
AndroidSupportInjectionModule.class,
AppModule.class,
ActivityBuilderModule.class,
ServiceBuilderModule.class
})
#Singleton
public interface AppComponent {
#Component.Builder
interface Builder {
#BindsInstance
Builder application(App application);
AppComponent build();
}
void inject(App app);
}
then override the onCreate method of your service and add AndroidInjection.inject(this)
like below code :
public class MyService extends Service {
#Override
public void onCreate() {
AndroidInjection.inject(this);
super.onCreate();
}
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
}
code in kotlin is exact conversion of the code above. hope this helps some coders from now on.