引起原因:java.lang.NoSuchMethodException:<init> [class android.app.Application]-viewmodel

时间:2019-04-11 06:29:38

标签: android android-viewmodel

我正在android应用中创建自己的viewmodel。
启动应用程序后,它崩溃了,我得到了错误

  

“原因:java.lang.NoSuchMethodException:[类android.app.Application]”

1。查看模型类:

public class MainViewModel extends AndroidViewModel implements OnCommunicationListener {

public MainViewModel(@NonNull Application application, DeviceData deviceData) {
        super(application);

….
}

2。查看模型工厂

public class ViewModelFactory extends ViewModelProvider.AndroidViewModelFactory {

    @NonNull
    private final Application application;
    private final DeviceData deviceData;

    public ViewModelFactory(@NonNull Application application, DeviceData deviceData) {
        super(application);
        this.application = application;
        this.deviceData = deviceData;
    }

    @NonNull
    @Override
    public <T extends ViewModel> T create(@NonNull Class<T> modelClass) {
        if (modelClass.isAssignableFrom(MainViewModel.class)) {
            return (T) new MainViewModel(application, deviceData);
        }
        throw new IllegalArgumentException("Unknown ViewModel class");
    }
}

3。主要活动课程

 viewModel = ViewModelProviders.of(this).get(MainViewModel.class);

App crashes when the following line executed in the main activity

 viewModel = ViewModelProviders.of(this).get(MainViewModel.class);

1 个答案:

答案 0 :(得分:1)

您需要将viewmodel工厂传递给of调用,否则您的工厂将无法使用。

viewModel = ViewModelProviders.of(this, viewModelFactoryInstance).get(MainViewModel.class);