If you want to use context in view model, you can't use ViewModel as it does not provide you context needed for creating Database. So Android architecture components introduced AndroidViewModel. If we use ViewModelProvider(this).get(ProductListingVM::class.java), it will cause error "java.lang.Class<com.example.swapnil.sat.models.ProductListingVM> has no zero argument constructor" thrown at runtime. So, how to use it? We shall pass AndroidViewModelFactory instance while creating the ViewModelProvider.
Let's have a look.
MainActivity.kt
Let's have a look.
MainActivity.kt
import androidx.appcompat.app.AppCompatActivity
import androidx.lifecycle.ViewModelProvider
class MainActivity : AppCompatActivity() {
lateinit var viewModel: ProductListingVMoverride fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main)viewModel=ViewModelProvider(this,ViewModelProvider.AndroidViewModelFactory(application))
.get(ProductListingVM::class.java)........}}ProductListingVM.ktclass ProductListingVM(private val applicationInstance: Application): AndroidViewModel(applicationInstance) {private var appDatabase = SatDatabase.getDatabase(applicationInstance)}