2

If we rotate the screen activity will recreate, but if we use ViewModel values will be retain. So the question is, if we have used ViewModel and we rotate the screen, will our activity recreate and call onCreate, onStart, onResume?

Aditya Vyas-Lakhan
  • 13,409
  • 16
  • 61
  • 96

2 Answers2

2

When you rotate your device and the screen changes orientation, Android restarts the running Activity ( onDestroy() is called, followed by onCreate()). Android does this so that your application can reload resources based on the new configuration.

A “ViewModel” is a class designed to survive configuration changes (Example: Screen Rotation) and can preserve the information necessary for the View. When fragment/activity is destroyed by changing the configuration or rotation of the device, its “ViewModel” will not be destroyed and a new instance of View will be reconnected to the same “ViewModel”.

Take an example, let in an activity "A", a text is shown in the view using a TextView. The text to set in that Textview is fetched by calling an api using the ViewModel. Remember, the api call was made when the Screen was in "Portrait" orientation. If you change orientation to "Landscape" then the api call will happen again. Changing screen orientation back and forth might cause a mess as we are dealing with api calls.

For this reason, we need to save the data in the ViewModel. When the screen is rotated, onResume() is called, inside onResume() we need to set the data again in the view extracting it from our ViewModel.

In Activity "A":

public void onResume(){
    super.onResume();
    String text = mViewModel.getData();
    
}

ViewModel:

private String data;

public boolean getData(){
    return data;
}

public void setData (String data) {
    this.data = data;
}

Remember to handle null pointer exception, it happens a lot while the screen orientation changes.

1

Yes, activity will be getting recreated so onCreate(), onStart(), onResume() will be getting called.

The ViewModel class is designed to store and manage UI-related data in a lifecycle conscious way. The ViewModel class allows data to survive configuration changes such as screen rotations.

ViewModel will hold the data on activity recreation (survive configuration changes). So, we can achieve the data persistance using the view model.

Revanth Kausikan
  • 673
  • 1
  • 9
  • 21