0

firstly I want to say I am sorry. I am newbie in MVVM. I want to know how to retain the data in viewmodel ??

For example I have followed this codelab tutorial https://codelabs.developers.google.com/codelabs/android-lifecycles/#0.

  1. I try to kill the apps then go back into the apps but the data is not saved .Why?

  2. I tried to make new activity by intent it. I ln new activity I implement the same code as statelifecyle. But why when I backpressed and try to enter back the newactivity the data is not saved ?

1 Answers1

0

To answer your questions:

  1. Data in ViewModel is only persisted throughout the lifecycle of your activity. So if your app dies, your data is not saved. If you want it to persist, consider integrating an off-line data persistence library like Room or you can also use SharedPreferences depending on your use case.

  2. According to this post: Android LiveData - how to reuse the same ViewModel on different activities?

When you call ViewModelProviders.of(this), you actually create/retain a ViewModelStore which is bound to this, so different Activities have different ViewModelStore and each ViewModelStore creates a different instance of a ViewModel using a given factory, so you can not have the same instance of a ViewModel in different ViewModelStores

In other words, different activities cannot share a single ViewModel. So if you want to switch pages while retaining data in your ViewModel, consider using fragments inside your activity instead.

Christilyn Arjona
  • 2,173
  • 3
  • 13
  • 20
  • Actually I also have followed this tutorial using room but also fail to retain the data.https://codelabs.developers.google.com/codelabs/android-training-livedata-viewmodel/#13 – AndroidMalaya Jan 01 '20 at 05:04