本文介绍了使用 MVVM 时无法创建类 ViewModel 的实例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了 ViewModel 类,并尝试创建我的实例ViewModel 类使用 ViewModelProvider.在运行时,我收到此错误"无法创建 className ViewModel 类的实例.这里有所需代码:

I have created ViewModel class, and trying to create an instance of myViewModel class using ViewModelProvider. At runtime, I'm getting this error"Cannot create an instance of class className ViewModel. Here are therequired codes:

MainActivity.java

public class MainActivity extends AppCompatActivity {

    MainActivityViewModel mainActivityViewModel;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        mainActivityViewModel = new ViewModelProvider(this).get(MainActivityViewModel.class);
    }
}

MainActivityViewModel.java

public class MainActivityViewModel extends AndroidViewModel {
    private BookShopRepository bookShopRepository;

    public MainActivityViewModel(@NonNull Application application) {
        super(application);
        bookShopRepository = new BookShopRepository(application);
    }
}

BookShopRepository.java

public class BookShopRepository {

    private CategoryDAO categoryDAO;
    private BookDAO bookDAO;
    private LiveData<List<Category>> categories;
    private LiveData<List<Book>> books;

    public BookShopRepository(Application application) {
        BooksDatabase booksDatabase = BooksDatabase.getInstance(application);
        categoryDAO = booksDatabase.categoryDAO();
        bookDAO = booksDatabase.bookDAO();
    }
}

build.gradle 依赖

dependencies {
    def room_version = "2.2.5"
    def lifecycle_version = "2.2.0"

    // ViewModel
    implementation "androidx.lifecycle:lifecycle-viewmodel:$lifecycle_version"
    // LiveData
    implementation "androidx.lifecycle:lifecycle-livedata:$lifecycle_version"
    annotationProcessor "androidx.lifecycle:lifecycle-compiler:$lifecycle_version"

    implementation "androidx.room:room-runtime:$room_version"
    annotationProcessor "androidx.room:room-compiler:$room_version"

    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation 'androidx.appcompat:appcompat:1.1.0'
    implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'androidx.test:runner:1.2.0'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0'
}

错误信息:

Process: com.example.ch5project, PID: 3754
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.ch5project/com.example.ch5project.MainActivity}: java.lang.RuntimeException: Cannot create an instance of class com.example.ch5project.viewmodel.MainActivityViewModel
    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2325)
    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2387)
    at android.app.ActivityThread.access$800(ActivityThread.java:151)
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1303)
    at android.os.Handler.dispatchMessage(Handler.java:102)
    at android.os.Looper.loop(Looper.java:135)
    at android.app.ActivityThread.main(ActivityThread.java:5254)
    at java.lang.reflect.Method.invoke(Native Method)
    at java.lang.reflect.Method.invoke(Method.java:372)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
    Caused by: java.lang.RuntimeException: Cannot create an instance of class com.example.ch5project.viewmodel.MainActivityViewModel
    at androidx.lifecycle.ViewModelProvider$NewInstanceFactory.create(ViewModelProvider.java:221)
    at androidx.lifecycle.ViewModelProvider.get(ViewModelProvider.java:187)
    at androidx.lifecycle.ViewModelProvider.get(ViewModelProvider.java:150)
    at com.example.ch5project.MainActivity.onCreate(MainActivity.java:24)
    at android.app.Activity.performCreate(Activity.java:5990)
    at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1106)
    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2278)
    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2387) 
    at android.app.ActivityThread.access$800(ActivityThread.java:151) 
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1303) 
    at android.os.Handler.dispatchMessage(Handler.java:102) 
    at android.os.Looper.loop(Looper.java:135) 
    at android.app.ActivityThread.main(ActivityThread.java:5254) 
    at java.lang.reflect.Method.invoke(Native Method) 
    at java.lang.reflect.Method.invoke(Method.java:372) 
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903) 
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698) 
    Caused by: java.lang.InstantiationException: class com.example.ch5project.viewmodel.MainActivityViewModel has no zero argument constructor
    at java.lang.Class.newInstance(Class.java:1597)
    at androidx.lifecycle.ViewModelProvider$NewInstanceFactory.create(ViewModelProvider.java:219)
    at androidx.lifecycle.ViewModelProvider.get(ViewModelProvider.java:187) 
    at androidx.lifecycle.ViewModelProvider.get(ViewModelProvider.java:150) 
    at com.example.ch5project.MainActivity.onCreate(MainActivity.java:24) 
    at android.app.Activity.performCreate(Activity.java:5990) 
    at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1106) 
    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2278) 
    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2387) 
    at android.app.ActivityThread.access$800(ActivityThread.java:151) 
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1303) 
    at android.os.Handler.dispatchMessage(Handler.java:102) 
    at android.os.Looper.loop(Looper.java:135) 
    at android.app.ActivityThread.main(ActivityThread.java:5254) 
    at java.lang.reflect.Method.invoke(Native Method) 
    at java.lang.reflect.Method.invoke(Method.java:372) 
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903) 
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698) 
    Caused by: java.lang.NoSuchMethodException: <init> []
    at java.lang.Class.getConstructor(Class.java:531)
    at java.lang.Class.getDeclaredConstructor(Class.java:510)
    at java.lang.Class.newInstance(Class.java:1595)
    at androidx.lifecycle.ViewModelProvider$NewInstanceFactory.create(ViewModelProvider.java:219) 
    at androidx.lifecycle.ViewModelProvider.get(ViewModelProvider.java:187) 
    at androidx.lifecycle.ViewModelProvider.get(ViewModelProvider.java:150) 
    at com.example.ch5project.MainActivity.onCreate(MainActivity.java:24) 
    at android.app.Activity.performCreate(Activity.java:5990) 
    at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1106) 
    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2278) 
    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2387) 
    at android.app.ActivityThread.access$800(ActivityThread.java:151) 
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1303) 
    at android.os.Handler.dispatchMessage(Handler.java:102) 
    at android.os.Looper.loop(Looper.java:135) 
    at android.app.ActivityThread.main(ActivityThread.java:5254) 
    at java.lang.reflect.Method.invoke(Native Method) 
    at java.lang.reflect.Method.invoke(Method.java:372) 
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903) 
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698) 
```text

推荐答案

根据 Lifecycle 2.2.0 发行说明:

ViewModelProviders.of() 弃用:ViewModelProviders.of() 已弃用.您可以将 FragmentFragmentActivity 传递给新的 ViewModelProvider(ViewModelStoreOwner) 构造函数,以在使用 .

最后一部分很重要,否则 new ViewModelProvider(this) 只会使用您在异常中看到的 NewInstanceFactory,它不支持 AndroidViewModel.AppCompat 1.1.0 仅依赖于 Fragment 1.1.0,因此您没有获得对您正在使用的 ViewModelProvider 构造函数的支持.

That last part is important, as otherwise new ViewModelProvider(this) will only use the NewInstanceFactory you see in the exception, which doesn't support AndroidViewModel. AppCompat 1.1.0 only depends on Fragment 1.1.0, so you're not getting the support for the ViewModelProvider constructor you're using.

因此,您应该升级到 Fragment 1.2.0 或更高版本(当前为 1.2.4):

Therefore, you should upgrade to Fragment 1.2.0 or higher (currently 1.2.4):

implementation 'androidx.fragment:fragment:1.2.4'

这篇关于使用 MVVM 时无法创建类 ViewModel 的实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

06-14 21:18