Reputation:
I have been trying to implement the LiveData and View Model. In this App, a number is displayed on the screen and we can add five or minus one. Now Earlier I used viewModelProvider but now it is deprecated and I am using "by viewmodels" but it is showing ann error
fragOne.kt
class fragOne : Fragment() {
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
// Inflate the layout for this fragment
var binding = DataBindingUtil.inflate<FragmentFragoneBinding>(
inflater,
R.layout.fragment_fragone,
container,
false
)
//viewModel = ViewModelProviders.of(this).get(fragViewModel::class.java)
// Create the observer which updates the UI.
val viewModel: fragViewModel by **viewModels()**
val nameObserver = Observer<Int> {
viewModel.num.value=it
}
// Observe the LiveData, passing in this activity as the LifecycleOwner and the observer.
viewModel.num.observe(viewLifecycleOwner,nameObserver)
// setting on Click listener for add button
binding.add.setOnClickListener()
{
//updateNumber()
viewModel.num.setValue(viewModel.addFive())
}
// setting on on Click Listener for minus button
binding.minus.setOnClickListener()
{
viewModel.num.setValue(viewModel.minusOne())
//updateNumber()
}
return binding.root
}
// Always call the superclass so it can save the view hierarchy state
}
fragViewModel
import androidx.lifecycle.ViewModel
class fragViewModel:ViewModel()
{
val num: MutableLiveData<Int> by lazy {
MutableLiveData<Int>()
}
// Initializing num=0
init {
num .value= 0
}
// Functions to add five or subtract one
fun addFive():Int
{
var newNumber:Int?=num.value
return newNumber?.plus(5)?:0
}
fun minusOne():Int
{
var newNumber:Int?=num.value
return newNumber?.minus(1)?:0
}
}
In fragOne there is an error showing in by viewModels . So whats the error. please let me know if anyone wants the code I will upload it in Github
build.gradle
def lifecycle_version = "2.2.0"
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
implementation 'androidx.appcompat:appcompat:1.1.0'
implementation 'androidx.core:core-ktx:1.2.0'
implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
implementation 'androidx.legacy:legacy-support-v4:1.0.0'
testImplementation 'junit:junit:4.12'
androidTestImplementation 'androidx.test.ext:junit:1.1.1'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0'
implementation 'androidx.lifecycle:lifecycle-extensions:2.2.0'
implementation "androidx.core:core-ktx:1.2.0"
// ViewModel
implementation "androidx.lifecycle:lifecycle-viewmodel-ktx:$lifecycle_version"
}
Upvotes: 8
Views: 10307
Reputation: 29
First add the the following dependencies to use viewModels(), (latest version)
implementation("androidx.navigation:navigation-fragment-ktx:$nav_version")
implementation("androidx.navigation:navigation-ui-ktx:$nav_version")
implementation "androidx.lifecycle:lifecycle-viewmodel-ktx:$lifecycle_version"
Then you can use in your fragment
private val yourViewModel: YourViewModel by viewModels { // scope is this fragment
YourViewModelFactory(YourRepository(YourItemDatabase.invoke(requireContext())))
}
Or
private val yourViewModel: YourViewModel by activityViewModels()// scope is it's activity
Upvotes: 0
Reputation: 630
Since you are using a fragment in addition implementation "androidx.core:core-ktx:1.3.1"
adding this to your build.gradle
implementation "androidx.fragment:fragment-ktx:1.2.5"
Usage in Fragment
// 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>()
Upvotes: 11