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)
.
@OverridepublicvoidonSaveInstanceState(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:
@OverridepublicvoidonRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
// Restore UI state from the savedInstanceState.// This bundle has also been passed to onCreate.booleanmyBoolean= savedInstanceState.getBoolean("MyBoolean");
doublemyDouble= savedInstanceState.getDouble("myDouble");
intmyInt= savedInstanceState.getInt("MyInt");
StringmyString= savedInstanceState.getString("MyString");
}
Post a Comment for "Orientation Changes In Android"