Home > Software design >  How do I implement ViewModel inside a Fragment?
How do I implement ViewModel inside a Fragment?

Time:12-14

I tried to implement ViewModel inside Fragment like this:

class myFragment: Fragment() {


    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?

CodePudding user response:

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>()
  • Related