Orientation Changes In Android
I am using getLastNonConfigurationInstance() to save object while changing orientation in my activity. now it is deprecated. What is the best way of alternative? the documentation
Solution 1:
For saving state, use onSaveInstanceState(Bundle savedInstanceState)
. You can restore saved state either in onCreate
or in onRestoreInstanceState(Bundle savedInstanceState)
.
@Override
public void onSaveInstanceState(Bundle savedInstanceState) {
// Save UI state changes to the savedInstanceState.
// This bundle will be passed to onCreate if the process is
// killed and restarted.
savedInstanceState.putBoolean("MyBoolean", true);
savedInstanceState.putDouble("myDouble", 1.9);
savedInstanceState.putInt("MyInt", 1);
savedInstanceState.putString("MyString", "Hello Android");
super.onSaveInstanceState(savedInstanceState);
}
The Bundle is essentially a way of storing a Key-Value Pair" map, and it will get passed in to onCreate and also onRestoreInstanceState where you would extract the values like this:
@Override
public void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
// Restore UI state from the savedInstanceState.
// This bundle has also been passed to onCreate.
boolean myBoolean = savedInstanceState.getBoolean("MyBoolean");
double myDouble = savedInstanceState.getDouble("myDouble");
int myInt = savedInstanceState.getInt("MyInt");
String myString = savedInstanceState.getString("MyString");
}
Post a Comment for "Orientation Changes In Android"