Collectives™ on Stack Overflow

Find centralized, trusted content and collaborate around the technologies you use most.

Learn more about Collectives

Teams

Q&A for work

Connect and share knowledge within a single location that is structured and easy to search.

Learn more about Teams private val viewModelProvider by lazy { ViewModelProvider(requireActivity()) } private val myViewModel by lazy { viewModelProvider.get( ViewModel::class.java

The error is:

E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.net2software.mobile.mpos_cirebon.debug, PID: 15298
java.lang.RuntimeException: Cannot create an instance of class com.mypackagename.viewmodel.viewmodelClass

How can I fix this?

You can use Fragment Extension

def fragment_version = "1.4.0"
implementation "androidx.fragment:fragment-ktx:$fragment_version"

Fragment View Model

private val viewModel by viewModels<ViewModel>()

Activity Shared ViewModel between fragments

private val activityViewModel by activityViewModels<ViewModel>()
                I got an error, it said:   The minCompileSdk (31) specified in a dependency's AAR metadata (META-INF/com/android/build/gradle/aar-metadata.properties) is greater than this module's compileSdkVersion (android-30). Dependency: androidx.fragment:fragment-ktx:1.4.0. AAR metadata file: C:\Users\lenovo.gradle\caches\transforms-2\files-2.1\642b3a1daa9bf0ed0ed57b9f44a43ba8\jetified-fragment-ktx-1.4.0\META-INF\com\android\build\gradle\aar-metadata.properties.
– Kafabih
                Dec 13, 2021 at 10:54
                alright, it can build  but I got confused... u said:  Fragment View Model  private val viewModel by viewModels<ViewModel>( ),  how to implement this into my code...,  private val viewModelProvider by lazy { ViewModelProvider(requireActivity()) }     private val myViewModel by lazy {         viewModelProvider.get(              ViewModel::class.java <- this is my viewmodel         )     }  and is it possible to implement viewmodel in fragment alone(without requireactivity) ?
– Kafabih
                Dec 13, 2021 at 11:15
                Now you don't need to use  viewModelProvider to create view model just write private val viewModel by viewModels<ViewModel>() and inside viewModels<?> this is your view model class
– AmrDeveloper
                Dec 13, 2021 at 11:19
                thank you... it works... but got different error, it said: no injector found,  is there any supported injector for the lib you've mentioned ? I use dagger com.google.dagger:dagger:2.37  anyway, I'll upvote your answer for now
– Kafabih
                Dec 13, 2021 at 12:04
        

Thanks for contributing an answer to Stack Overflow!

  • Please be sure to answer the question. Provide details and share your research!

But avoid

  • Asking for help, clarification, or responding to other answers.
  • Making statements based on opinion; back them up with references or personal experience.

To learn more, see our tips on writing great answers.