Android Mvvm, app with more than one activity


i am new in android, i am working on an app that retrieve data from server using retrofit and kodein and MvvM in kotlin
i set a Navigation drawer in my app and the purpose is that when i click on the item of navigation drawer
new activity opens and in this activity i want show recyclerview
but when new activty opens recyclerview cant set listitem on recycler
i debug my code in my repositories and viewmodel class and i see that they received data
i debug my code in new activty and i see that viewmodel cant receive those data and set a invalid icon next to my code in viewmodel.observe

this is my repository class:

 fun getdigitalproduct(): LiveData<List<DigitalProduct>>{
    val dpData:MutableLiveData<List<DigitalProduct>> = MutableLiveData<List<DigitalProduct>>()
    val apiClient = ApiClient()

    val call:Call<List<DigitalProduct>> = apiClient.getClient().create(
    call.enqueue(object : Callback<List<DigitalProduct>>{
        override fun onResponse(
            call: Call<List<DigitalProduct>>,
            response: Response<List<DigitalProduct>>
        ) {
            dpData.value = response.body()

        override fun onFailure(call: Call<List<DigitalProduct>>, t: Throwable) {
             dpData.value = null

    return dpData

this is for ViewModel

var repoDigitalProduct: LiveData<List<DigitalProduct>> = repositorys.getdigitalproduct()
fun getdigitalproduct(): LiveData<List<DigitalProduct>>{
    return repoDigitalProduct

this is for new activity:

  private fun getDigitalProduct() {
    viewModel.getdigitalproduct().observe(this, Observer {

this is digipro:

var digipro: ArrayList<DigitalProduct> = ArrayList()

and this i use this code in oncreate method in new activity:

  viewModel = ViewModelProviders.of(this, factory).get(

i use viewmodelprovider.of code in Mainactivity too

this is for setdigitalProductRecycler:

 private fun setdigitalProductRecycler() {
    val digiproRecycler = digital_product_recycler
    digiproRecycler.layoutManager =
        LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, true)
    digiproRecycler.adapter = DigitalProductAdapter(digipro)

my codes works in Mainactivity but when i try it in new activity………

what should i do?


The best way to solve this issue is create your viewmodel in activity or you can use shared viewmodel. So your viewmodel will retain as your activity retain

Answered By – Yehezkiel L

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published