Retain data across screen rotations change on Android
Retain data across screen rotations change in Android is such a pain. Luckily, Architecture Components provide a convenient way to survive from this. The new class called
ViewModel, it will automatically retain data during on configuration changes. There are only 2 steps to archive it:
- Declare a model extends ViewModel
- Instance model through ViewModelProviders
A quick look at lifecycle
No matter what you do, it will keep the object until the activity reach to
finished() event, which you get the model from
Enough show me the code
1. Extends ViewModel
The model can hold complex data. By implementing this, you saved a lot of time, instead of writing a dozen lines of put and get in
onSaveInstanceState()and have to declare several key constant lines for each of them.
This could be called one time in
onCreate() and the model can be a field in fragment/activity without fear of losing its data. The model can be a local field and query multiple time through ViewModelProviders, it’s still the same object.
That’s it! No need to mess up code in
onSaveInstanceState(). This approach keeps code clean and simple.