I\'m at the very beginning of a new Android project. After playing around with MVP in my last project, I want to implement MVVM with Data Binding this time.
I have a
You need to save state of your view model by overriding of method onSaveInstanceState()in your activity class and restore it in onCreate() method.
private static final String QUESTION = "testViewModel.question";
private TestViewModel mTestViewModel;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ActivityTestBinding binding = DataBindingUtil.setContentView(this, R.layout.activity_test);
mTestViewModel = new TestViewModel();
// Check whether we're recreating a previously destroyed instance
if (savedInstanceState != null) {
// restore view model state
String questionVal = savedInstanceState.getString(QUESTION, "");
mTestViewModel.setQuestion(questionVal);
}
binding.setVm(mTestViewModel);
}
@Override
public void onSaveInstanceState(Bundle savedInstanceState) {
// Save current view model state
savedInstanceState.putString(QUESTION, mTestViewModel.getQuestion());
// Always call the superclass so it can save the view hierarchy state
super.onSaveInstanceState(savedInstanceState);
}
More information about "save-restore" technology you can read at this part of documentation