Saturday, February 29, 2020

Using AndroidViewModel for accessing application context

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

import androidx.appcompat.app.AppCompatActivity
import androidx.lifecycle.ViewModelProvider

class MainActivity : AppCompatActivity() {

lateinit var viewModel: ProductListingVM

  override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_main)
    viewModel=ViewModelProvider(this,
        ViewModelProvider.AndroidViewModelFactory(application))
        .get(ProductListingVM::class.java)

........
  }
}


ProductListingVM.kt

class ProductListingVM(private val applicationInstance: Application) 
  : AndroidViewModel(applicationInstance) {
  
  private var appDatabase = SatDatabase.getDatabase(applicationInstance)
}

No comments:

Post a Comment

Securing Microservices with JWT Authentication and Data Encryption

Securing Microservices with JWT Authentication and Data Encryption Securing Microservices with JWT A...