简体   繁体   English

使用 MVVM 时无法创建 class ViewModel 的实例

[英]Cannot create instance of class ViewModel while using MVVM

I have created ViewModel class, and trying to create an instance of my ViewModel class using ViewModelProvider.我创建了ViewModel class,并尝试使用 ViewModelProvider 创建我的ViewModel class 的实例。 At runtime, I'm getting this error "Cannot create an instance of class className ViewModel . Here are the required codes:在运行时,我收到此错误“无法创建 class className ViewModel的实例。这是所需的代码:

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

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'
}

ERROR MESSAGE:错误信息:

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

As per the Lifecycle 2.2.0 release notes :根据Lifecycle 2.2.0 发行说明

ViewModelProviders.of() deprecation: ViewModelProviders.of() has been deprecated. ViewModelProviders.of()弃用: ViewModelProviders.of()已弃用。 You can pass a Fragment or FragmentActivity to the new ViewModelProvider(ViewModelStoreOwner) constructor to achieve the same functionality when using Fragment 1.2.0 .您可以将FragmentFragmentActivity传递给新的ViewModelProvider(ViewModelStoreOwner)构造函数,以在使用Fragment 1.2.0实现相同的功能。

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 .最后一部分很重要,否则new ViewModelProvider(this)将仅使用您在异常中看到的NewInstanceFactory ,它不支持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. AppCompat 1.1.0 仅依赖于 Fragment 1.1.0,因此您没有获得对您正在使用的ViewModelProvider构造函数的支持。

Therefore, you should upgrade to Fragment 1.2.0 or higher (currently 1.2.4):因此,您应该升级到 Fragment 1.2.0 或更高版本(当前为 1.2.4):

implementation 'androidx.fragment:fragment:1.2.4'

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM