Home > Software engineering >  how to implement ViewModel Inside Fragment
how to implement ViewModel Inside Fragment

Time:12-13

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
        )
    }
    ....
    }

and I get error said :

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

what is wrong ? and how to fix it ?

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