2017-06-28 79 views
1

我正在使用Dagger2在我的所有應用程序中注入依賴項。使用匕首注入依賴關係時發生ClassCastException

幾天前,我開始爲三星Android 7.0(僅限於這些)設備的應用之一獲取崩潰報告。

java.lang.RuntimeException: 
    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2924) 
    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2985) 
.. 
Caused by: java.lang.ClassCastException: 
    at de.package.name.MyApplication.get(MyApplication.java:43) 
    at de.package.name.ui.base.BaseActivity.onCreate(BaseActivity.java:53) 
    at de.package.name.ui.startup.StartupActivity.onCreate(StartupActivity.java:26) 
    at android.app.Activity.performCreate(Activity.java:6912) 
    at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1126) 
    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2877) 

所有MyApplication類:

public class MyApplication extends MultiDexApplication { 

    private AppComponent appComponent; 

    @Override 
    public void onCreate() { 
     super.onCreate(); 
     setupAppComponent(); 
    } 

    private void setupAppComponent() { 
     appComponent = DaggerAppComponent.builder() 
       .appModule(new AppModule(this)) 
       .userApiModule(new UserApiModule()) 
       .build(); 
     appComponent.inject(this); 
    } 

    public static MyApplication get(Context context) { 
     return (MyApplication) context.getApplicationContext(); 
    } 
} 

的BaseActivity類的相關部分:

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

最後,StartupActivity部分:

@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setupComponent(MyApplication.get(this).getAppComponent()); 
    setContentView(R.layout.activity_startup); 

    startupPresenter.bindView(this); 
} 

public void setupComponent(AppComponent appComponent) { 
    startupComponent = DaggerStartupComponent.builder() 
      .appComponent(appComponent) 
      .startupModule(new StartupModule()) 
      .build(); 
    startupComponent.inject(this); 
} 

我已經更新匕首最近的訴ersion(現在爲2.11)。但我對這個問題沒有任何想法。另外,我無法在Samsung S8 7.0設備上重現它。

所以,如果你有任何想法,請讓我知道!

乾杯

編輯: 如果有人運行到這個問題。看看這裏:RuntimeException with Dagger 2 on Android 7.0 and Samsung devices 這可能是你的解決方案。

回答

1

這與匕首無關。問題就在這裏:

return (MyApplication) context.getApplicationContext(); 

通過getApplicationContext()返回的Context保證是你Application實例。我遇到的唯一情況是在模擬器中,但它總是可能的。

我更喜歡這種方法:

private static MyApplication gInstance; 

@Override 
public void onCreate() { 
    gInstance = this; 
} 

public static MyApplication instance() { 
    return gInstance; 
} 

,因爲在創建Application實例是創建任何其他Android組件之前,其onCreate被稱爲這是安全的。

+0

感謝您的建議。不幸的是,這個變化導致'NullpointerExceptions'訪問實例。這怎麼可能? :/ – chrjs

+0

@chrjs您是否在清單中設置了自定義的應用程序類?您是否在生命週期方法之外調用'instance()'(例如,在字段初始值設定項?) –

+0

是的,它在清單中設置。並且只能通過BaseActivity的'onCreate'來訪問 – chrjs