I am working with Single viewModel for the Activity and all of it's fragment.
So to initialise viewmodel
if have to write this setup code in onActivityCreated
of all the fragment's
override fun onActivityCreated(savedInstanceState: Bundle?) { super.onActivityCreated(savedInstanceState) viewModel = ViewModelProviders.of(activity!!).get(NoteViewModel::class.java) }
I was going thorough the Android KTX extension page:(refer here)
and i found i can initialise view model like this:
// Get a reference to the ViewModel scoped to this Fragment val viewModel by viewModels<MyViewModel>() // Get a reference to the ViewModel scoped to its Activity val viewModel by activityViewModels<MyViewModel>()
So I added below dependency's to my gradle(app):
//ktx android implementation 'androidx.core:core-ktx:1.0.2' implementation 'androidx.fragment:fragment-ktx:1.0.0' implementation "androidx.lifecycle:lifecycle-extensions:2.0.0"
But when i try to use viewModels/activityViewModels
in my application their reference in not found.
I want help in how to use these extension's with some basic example i tried searching for examples haven't found any.
You should have an instance of fragments inside the activity. Your fragment already holding a reference to the ViewModel. Delete these line from the activity -> : viewModelRoutesFragment = new ViewModelProvider(this).
In order to use ViewModel, add a dependency on androidx. lifecycle's lifecycle-viewmodel-ktx library in your module's build. gradle file and sync the changes. For every Activity or Fragment, whose data you want to preserve using ViewModel, creating a separate class is highly recommended.
In android, we can use ViewModel to share data between various fragments or activities by sharing the same ViewModel among all the fragments and they can access everything defined in the ViewModel. This is one way to have communication between fragments or activities.
Atlast we we have got stable version.
After moving to implementation 'androidx.fragment:fragment-ktx:1.1.0'
i faced another issue.
Cannot inline bytecode built with JVM target 1.8 into bytecode that is being built with JVM target 1.6
compileOptions { sourceCompatibility = 1.8 targetCompatibility = 1.8 } kotlinOptions { jvmTarget = "1.8" }
reference
After applying all the above the issue's is resolved.
try
implementation 'androidx.fragment:fragment-ktx:1.1.0-beta02'
This is no longer in beta. It works with the latest stable version at the time of writing. You will also need to import it in your fragment's Kotlin file.
implementation 'androidx.fragment:fragment-ktx:1.3.2'
import androidx.fragment.app.activityViewModels
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With