2017-08-16 22 views
-1

我在我的應用中使用Dagger。 正如文檔所述,我在Application類中將它作爲privatestatic類成員進行安裝,並在需要時將其獲得getterDagger在SplashActivity處爲null

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

但有時當調用從getterSplashActivity(這是我的啓動Activityappcomponent是空的,所以我得到一個NullpointerException當我嘗試注入到SplashActivity匕首。 我不能重現這個問題,但我可以在Crashlytics中使用它。 如果用戶沒有關閉應用程序,但很長時間後會返回,可能會發生這種情況。在這種情況下,我再次調用SplashActivity並清除堆棧,因爲我必須重新啓動一些我可以在此處執行的操作。也許這就是appcomponent爲空時的一點。 我只能在SplashActivity以及僅有的Android 7.x(和一些6.x)中看到此問題。 現在我試圖讓appcomponent像singletone

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上找不到這樣的問題。 您認爲可能是什麼問題?重構的初始化會解決它嗎? 謝謝!

+0

請包括_all_受影響的相關代碼以及錯誤和實際堆棧跟蹤。我的猜測是該活動被破壞並重新創建,並且出於某種原因您不會重新創建該組件。 –

回答

0

終於我能夠重現這個問題。 我開始我的應用程序,比其他很多應用程序還是被殺了。此時,如果我從任務管理器或啓動器圖標啓動我的應用程序,則會發生此異常。我的應用程序類中的Appcomponent的私有靜態實例爲null。 所以現在我重構我AppComponent消氣,我把它作爲像這樣

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的init AppComponent的onCreate()一singletone,而現在它的工作原理。