0

I need this statement to activate dep. injection....

 ((App) getApplication()).inject(this);

            //or in fragment

 ((App) getActivity().getApplication()).inject(this);

 

This statement works fine in Activities and Fragments and Services, but how do I get this statement to work in non-activity/fragment/service based classes?

sirvon
  • 2,547
  • 1
  • 31
  • 55

2 Answers2

1

What dependency injection framework are you using? It looks like it might be dagger, in which case you can just use a constructor with an @Inject annotation and have the dependencies passed in through it like this (where Foo is your class and Bar is the dependency):

private final Bar mBar;

@Inject
public Foo(Bar bar) {
    mBar = bar;
}

In your module you'll need something like:

@Provides
public Foo providesFoo(Foo foo) {
    return foo;
}

If you aren't using dagger (and even if you are), I'd recommend making a static method in your application class to get the instance of your application to avoid casting it, and allow it to be accessible from anywhere within your app (although I'd personally only call it in Activities/Fragments/Services/etc.). I use something like this:

private static App sInstance;

public static App getInstance() {
    return sInstance;
}

@Overrride
public void onCreate() {
    super.onCreate();
    sInstance = this;
}
GeordieMatt
  • 1,236
  • 1
  • 9
  • 7
0

You can pass context from activity or fragment to Non Activity Class and alternate solution is that you can use application context. Like define a function

getContext()

in your application calls and return application context from it.

Hari Ram
  • 3,098
  • 5
  • 23
  • 30