Dagger 2 – how to inject only basic activities / fragments

I am studying dagger 2 from many sources, such as: http://fernandocejas.com/2015/04/11/tasting-dagger-2-on-android/ But I still haven't found the answer to the question

I work on a very complex application, which contains dozens of fragments and some activities I want to use di (dagger 2). For all these fragments and activities, I have a baseactivity and a basefragment. However, as far as I read and try, in order to use @ inject in my mainactivity, I must specify it in the component interface, It is also necessary to call getApplicationComponent ().Inject (this) in the onCreate method. When I perform this operation only for BaseActivity, I do not inject @Inject annotated fields into MainActivity. What is worse, I did not find this until the specific part of the code was executed and the NPE was thrown.

So far, this is a big problem for me, because this may be the reason for many crashes. I will need to specify dozens of fragments and activities in the Component interface, and don't forget to call inject. in every onCreate method.

I'm glad to hear about any solution because I really want to use di

Code example:

@Singleton
@Component(modules = ApplicationModule.class)
public interface ApplicationComponent {
    void inject(BaseActivity baseActivity);
    Analytics analytics();
}

public class BaseActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        this.getApplicationComponent().inject(this);
    }
}

public class MainActivity extends BaseActivity {
    @Inject
    Analytics analytics;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        analytics.log("event1"); // THROWS NPE!
    }
}

resolvent:

You cannot inject attributes into subclasses by injecting parent classes (because dagger2 works at compile time and cannot dynamically check annotated attributes in subclasses.)

You can move the analysis up to super and inject it there. To inject annotated fields into subclasses, you will have to call injection again here

You can create an abstract method in the base class. For example, you only need to process the injected inject (APP) in it. In this way, you won't "Miss" it

As stated in the official documentation:

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>