我在ViewModel工厂中实现ViewModel,并在Firebase crashlytics的某些设备上崩溃。
在我的设备上进行测试时,该应用程序不会崩溃。
这是与ViewModel相关的代码的一部分:
活动中(工厂注入了匕首2):
myViewModel = ViewModelProviders.of(this, myViewModelFactory).get(MyViewModel.class);
工厂:
public static class MyViewModelFactory implements ViewModelProvider.Factory {
private final MyRepository myRepository;
@Inject
public MyViewModelFactory(MyRepository myRepository) {
this.myRepository = myRepository;
}
@NonNull
@Override
@SuppressWarnings("unchecked")
public <T extends ViewModel> T create(@NonNull Class<T> modelClass) {
if (modelClass.isAssignableFrom(MyViewModel.class)) {
return (T) new MyViewModel(myRepository);
}
throw new IllegalArgumentException("Unknown ViewModel class");
}
}
视图模型构造函数:
public class MyViewModel extends ViewModel {
...
public MyViewModel(MyRepository myRepository) {
this.myRepository = myRepository;
}
...
}
即时通讯异常:
Caused by java.lang.InstantiationException: java.lang.Class<....MyViewModel> has no zero argument constructor
at java.lang.Class.newInstance(Class.java)
at androidx.lifecycle.ViewModelProvider$NewInstanceFactory.create(ViewModelProvider.java:152)
at androidx.lifecycle.ViewModelProvider$AndroidViewModelFactory.create(ViewModelProvider.java:211)
at androidx.lifecycle.ViewModelProvider.get(ViewModelProvider.java:135)
at androidx.lifecycle.ViewModelProvider.get(ViewModelProvider.java:103)
at .....MyActivity.onCreate(MyActivity.java:140)
at android.app.Activity.performCreate(Activity.java:7023)
at android.app.Activity.performCreate(Activity.java:7014)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1215)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2745)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2870)
at android.app.ActivityThread.-wrap11(Unknown Source)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1601)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:172)
at android.app.ActivityThread.main(ActivityThread.java:6590)
at java.lang.reflect.Method.invoke(Method.java)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:807)
您知道什么原因可能导致此问题吗?
谢谢
答案 0 :(得分:0)
我也遇到了类似的崩溃。问题是我在对ViewModelProvider.Factory
的某些调用中未能指定ViewModelProviders.of(...)
。实际上,它运行良好,直到系统破坏了我的活动为止。那就是崩溃发生的时间。
开发人员设置中的“不保留活动”选项对于调试此功能非常有用。