Touching again on the depreciated ViewModelProviders method and how I fixed it for chapter 9
Listing 9.1 app.build.gradle
dependencies {
def activity_version = "1.3.1"
def fragment_version = "1.3.6"
def lifecycle_version = "2.4.0-rc01"
implementation 'androidx.core:core-ktx:1.6.0'
implementation 'androidx.appcompat:appcompat:1.3.1'
implementation 'com.google.android.material:material:1.4.0'
implementation 'androidx.constraintlayout:constraintlayout:2.1.1'
// https://developer.android.com/jetpack/androidx/releases/lifecycle
// ViewModel
implementation("androidx.lifecycle:lifecycle-viewmodel-ktx:$lifecycle_version")
// ViewModel utilities for Compose
implementation("androidx.lifecycle:lifecycle-viewmodel-compose:$lifecycle_version")
// LiveData
implementation("androidx.lifecycle:lifecycle-livedata-ktx:$lifecycle_version")
// Lifecycles only (without ViewModel or LiveData)
implementation("androidx.lifecycle:lifecycle-runtime-ktx:$lifecycle_version")
// Saved state module for ViewModel
implementation("androidx.lifecycle:lifecycle-viewmodel-savedstate:$lifecycle_version")
implementation("androidx.activity:activity-ktx:$activity_version")
implementation("androidx.fragment:fragment-ktx:$fragment_version")
implementation("androidx.recyclerview:recyclerview:1.2.1")
// For control over item selection of both touch and mouse driven selection
implementation("androidx.recyclerview:recyclerview-selection:1.1.0")
testImplementation 'junit:junit:4.+'
androidTestImplementation 'androidx.test.ext:junit:1.1.3'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.4.0'
}
Listing 9.3 CrimeListFragment.kt
class CrimeListFragment : Fragment()
{
private lateinit var crimeRecyclerView: RecyclerView
private var adapter: CrimeAdapter? = null
//https://forums.bignerdranch.com/t/solution-to-deprecated-method-viewmodelproviders-of/16833/4
val factory by lazy { CrimeListViewModelFactory() }
private val crimeListViewModel: CrimeListViewModel by lazy {
ViewModelProvider(this@CrimeListFragment, factory).
get(CrimeListViewModel::class.java)
}
And extra class file CrimeListViewModelFactory.kt
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
class CrimeListViewModelFactory() : ViewModelProvider.Factory
{
override fun <T : ViewModel> create(modelClass: Class<T>): T {
return modelClass.getConstructor().newInstance()
}
}