How to save state in android using onsavedInstancestate or on restorestate. Save state in android using onSaveInstanceState

useful blog/video : 

https://www.youtube.com/watch?v=T6kNBq6Nvdg


https://developer.android.com/guide/components/activities/activity-lifecycle#java


----------------------------------------------------------------------------------------------

Override the onSaveInstanceState() method 
and put the values in the Bundle using put*() methods


retreieve them in teh onCreate method by creating a condition.


IMP : always call the super.onSaveInstanceState(savedInstanceState); . Before putting your values in the bundle or else they will get wiped our

onSaveInstanceState method gets called typically before/after onStop() is called. This varies from Android version to version. In the older versions it used to get before onStop().

onRestoreInstanceState method gets triggered only when something was saved in onSaveInstanceState method.
It gets called after onStart().


@Override
public void onSaveInstanceState(Bundle savedInstanceState) {
// Save the user's current game state
TextView textView1 = findViewById(R.id.textView1);
savedInstanceState.putString("mytext", (String) textView1.getText());

// Always call the superclass so it can save the view hierarchy state
super.onSaveInstanceState(savedInstanceState);
}

@Override
protected void onRestoreInstanceState(@NonNull Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);

// Check whether we're recreating a previously destroyed instance
if (savedInstanceState != null) {
// Restore value of members from saved state
TextView textView1 = findViewById(R.id.textView1);
textView1.setText(savedInstanceState.getString("mytext"));
}

}
}

For small Data (under 100KB ) , we can use "onSaveInstance" , but for large amount of data , we need to use ViewModel.

ViewModel is used to manage UI related things like maintaing the state and data of the UI , so that it can survive config changes.





Comments

Popular posts from this blog

React Js + React-Redux (part-2)

React Js + CSS Styling + React Router (part-1)

ViteJS (Module Bundlers, Build Tools)