QNA > W > Why Do We Use Android Support Injection In Our Fragment?

Why do we use Android support injection in our fragment?

I think you are talking about Dagger 2[1] and Dependency Injection[2].

Dependency injection is a design pattern based on the principle of Inversion of Control[3]. It states that a class should receive all its dependencies from outside and should not create dependencies itself.

For example:

Let say you have a class A

  1. class A { 
  2.  
  3. //constructor 
  4. A() {} 

And another class B

  1. class B { 
  2. private A a; 
  3.  
  4. //constructor 
  5. B() { 
  6. a = new A(); 

The problem with definition of class B is that it creates an object of class A inside its constructor. This makes testing of class B difficult as you don’t know how to provide instance of class A

A better way to write class B would be

  1. class B { 
  2. private A a; 
  3.  
  4. //constructor 
  5. B(A a) { 
  6. this.a = a; 

Now, to mock class B you have to mock class A and provide it externally. This is called constructor injection.

You can do the same injection while creating your Fragment. There is absolutely nothing wrong in it. But, Android System sometimes creates Fragment instances on its own (during device rotation and configuration changes, this is also the reason why we need to provide empty constructor in fragment). Hence, we need to inject dependencies some other way.

We use field injection for it. As under,

  1. class GameFragment extends Fragment { 
  2. @Inject GameService gameService; 
  3. @Inject GameViewmodel gameViewmodel; 
  4.  
  5. //empty constructor for android system use 
  6. public GameFragment() {} 
  7.  
  8. @Override 
  9. public void onCreate(Bundle savedInstanceState) { 
  10. AndroidSupportInjection.inject(this); 
  11. super.onCreate(savedInstanceState); 

Please see on line 10 above. This is where dependencies are injected. Also, note that Dagger cannot inject private fields and hence there is no private modifier with @Inject.

I hope this helps.

Footnotes

[1] Practical guide to Dagger 2[2] Dependency injection - Wikipedia[3] Inversion of control - Wikipedia

Di Lovash Fie

Cosa succede quando chiedi a Siri di Dio? :: Vale la pena comprare CS-Cart? O posso andare con Prestashop?
Link utili