我正在使用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 這可能是你的解決方案。
感謝您的建議。不幸的是,這個變化導致'NullpointerExceptions'訪問實例。這怎麼可能? :/ – chrjs
@chrjs您是否在清單中設置了自定義的應用程序類?您是否在生命週期方法之外調用'instance()'(例如,在字段初始值設定項?) –
是的,它在清單中設置。並且只能通過BaseActivity的'onCreate'來訪問 – chrjs