【问题标题】:Dagger is null at SplashActivity匕首在 SplashActivity 为空
【发布时间】:2017-08-16 10:14:04
【问题描述】:

我在我的应用中使用 Dagger。 正如文档所说,我在我的 Application 类中将它设置为 private static 类成员,并在我需要的地方通过 getter 获取它。

    private void initDagger() {
    appComponent = DaggerAppComponent
            .builder()
            .appModule(new AppModule(this))
            .build();
}

但有时当从我的SplashActivity(这是我的启动器Activity)调用getter 时,appcomponent 为空,所以当我尝试将SplashActivity 注入 Dagger 时,我得到一个NullpointerException。 我无法重现此问题,但我可以在 Crashlytics 中重现。 如果用户没有关闭应用程序,但在很长一段时间后返回,则可能会发生这种情况。在这种情况下,我再次调用SplashActivity 并清除堆栈,因为我必须重新初始化一些我可以在这里做的事情。也许这就是appcomponent 为空的时候。 我可以在 SplashActivity 和 Android 7.x(和一些 6.x)上看到这个问题。 现在我尝试像单音一样获得appcomponent

    public static AppComponent initDaggerAndGet(IndexApplication application){
    if(appComponent == null){
        synchronized (lock){
            if(appComponent==null)appComponent = DaggerAppComponent
                    .builder()
                    .appModule(new AppModule(application))
                    .build();
        }
    }
    return appComponent;
}

当我在SplashActivity 得到它并像这样重构initDagger() 方法时

    private void initDagger() {
    initDaggerAndGet(this);
}

正如我所写,我无法重现该问题,并且在 SO 上找不到类似问题的内容。 你认为可能是什么问题?重构的初始化会解决吗? 谢谢!

【问题讨论】:

  • 请包括所有受影响的相关代码以及错误和实际堆栈跟踪。我的猜测是该活动被销毁并重新创建,并且由于某种原因您没有重新创建组件。

标签: android dagger-2 dagger


【解决方案1】:

最后我能够重现该问题。 我启动了我的应用程序,但我的应用程序仍然被杀死了很多其他应用程序。此时,如果我从任务管理器或启动器图标启动我的应用程序,我会收到此异常。我的 Application 类中 Appcomponent 的私有静态实例为空。 所以现在我重构了我的 AppComponent getter,我得到它就像这样的单例

    public static AppComponent getAppComponent() {
    Logger.logAppComponent("");
    if (appComponent == null) {
        Logger.logAppComponent("AppComponent is null");
        synchronized (lock) {
            if (appComponent == null) {
                Logger.logAppComponent("Create still null, so create new AppComponent");
                appComponent = DaggerAppComponent
                        .builder()
                        .appModule(new AppModule(getApplication()))
                        .build();
            }
        }
    }
    Logger.logAppComponent("Return AppComponent");
    return appComponent;
}

而不是在Appliaciton的onCreate()中初始化AppComponent,现在可以了。

【讨论】:

    猜你喜欢
    • 2019-11-18
    • 2020-10-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多