mahdi pishguy mahdi pishguy - 1 month ago 7
Android Question

Android using Dependency Injection on Fragments

I can use Dependency Injection for

Realm
successful, i can use
@Inject
into activity without any problem, now i want to use that and inject that into Fragments, since i novice to use this method, i can't do that

ApplicationModule
class:

@Module
public class ApplicationModule {

@Provides
Context provideApplicationContext() {
return AlachiqApplication.getInstance();
}

@Provides
@Singleton
RealmConfiguration provideRealmConfiguration() {
final RealmConfiguration.Builder builder = new RealmConfiguration.Builder()
.schemaVersion(Migration.SCHEMA_VERSION)
.deleteRealmIfMigrationNeeded()
.migration(new Migration());
return builder.build();
}

@Provides
Realm provideDefaultRealm(RealmConfiguration config) {
return Realm.getInstance(config);
}
}


ApplicationComponent
class:

@Component(modules = ApplicationModule.class)
@Singleton
public interface ApplicationComponent {
void inject(ActivityRegister target);
void inject(ActivityMain target);
void inject(FragmentEbooks target);
void inject(FragmentDocuments target);
void inject(SocketServiceProvider target);
}


how can i edit or create other class component and module to inject realm into that? by the way, i have more fragment on my application

Thanks in advance

Answer

Just add another target method in your component like,

@Component(modules = ApplicationModule.class)
@Singleton
public interface ApplicationComponent {
  void inject(ActivityRegister target);
  void inject(ActivityMain target);
  void inject(SocketServiceProvider target);
  void inject(MyFragment target);
}

And in your fragment do similar thing what your doing in your activity.

public class MyFragment extends Fragment{
   @inject Realm realm;

   @Override
   protected void onCreate(Bundle savedInstanceState) {
    ((MyApplication) getActivity().getApplication()).getComponent().inject(this);
}