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?
void inject (ApplicationClass applicationClass); void inject (CustomIntentService intentService); void inject (SimpleIntentService service);- OnregsIntentServiceand inject into any intent service, it will be null because your class is notIntentService, it isWhateverService. - EpicPandaForce