I\'ve successfully implemented onRetainNonConfigurationInstance() for my main Activity
to save and restore certain critical components across screen orientation
Instead of using onSaveInstanceState
and onRestoreInstanceState
, you can also use a ViewModel. Make your data model extend ViewModel
, and then you can use ViewModelProviders
to get the same instance of your model every time the Activity is recreated:
class MyData extends ViewModel {
// have all your properties with getters and setters here
}
public class MyActivity extends FragmentActivity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// the first time, ViewModelProvider will create a new MyData
// object. When the Activity is recreated (e.g. because the screen
// is rotated), ViewModelProvider will give you the initial MyData
// object back, without creating a new one, so all your property
// values are retained from the previous view.
myData = ViewModelProviders.of(this).get(MyData.class);
...
}
}
To use ViewModelProviders
, add the following to dependencies
in app/build.gradle
:
implementation "android.arch.lifecycle:extensions:1.1.1"
implementation "android.arch.lifecycle:viewmodel:1.1.1"
Note that your MyActivity
extends FragmentActivity
instead of just extending Activity
.
You can read more about ViewModels here: