Skip to content

Instantly share code, notes, and snippets.

@reustonium
Last active March 28, 2016 18:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save reustonium/3f14dd5ed7fc03b93180 to your computer and use it in GitHub Desktop.
Save reustonium/3f14dd5ed7fc03b93180 to your computer and use it in GitHub Desktop.
Dagger 2 Inject problem: `Firebase` never get's injected into `FirebaseService.java`
@Singleton
@Component(modules = ApplicationModule.class)
public interface ApplicationComponent {
@ApplicationContext Context context();
Application application();
Firebase firebase();
}
@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
Firebase provideFirebase(@ApplicationContext Context context) {
Firebase.setAndroidContext(context);
return new Firebase(Util.FIREBASE_URL);
}
}
public class FirebaseService {
@Inject Firebase mFirebaseRef; //NEVER GET'S INJECTED!
@Override
public LoginResult signinWithEmail(final String email, final String password) {
mFirebaseRef.dostuff(); //THIS REFERENCE DOESN'T GET INJECTED!
}
}
public class MyActivity extends AppCompatActivity {
private ActivityComponent mActivityComponent;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
public ActivityComponent getActivityComponent() {
if (mActivityComponent == null) {
mActivityComponent = DaggerActivityComponent.builder()
.activityModule(new ActivityModule(this))
.applicationComponent(MyApplication.get(this).getComponent())
.build();
}
return mActivityComponent;
}
}
public class MyApplication extends Application {
ApplicationComponent mApplicationComponent;
@Override
public void onCreate() {
super.onCreate();
}
public static MyApplication get(Context context) {
return (MyApplication) context.getApplicationContext();
}
public ApplicationComponent getComponent() {
if (mApplicationComponent == null) {
mApplicationComponent = DaggerApplicationComponent.builder()
.applicationModule(new ApplicationModule(this))
.build();
}
return mApplicationComponent;
}
public void setComponent(ApplicationComponent applicationComponent) {
mApplicationComponent = applicationComponent;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment