Saving Activity state on Android when change orientation

In Android application when we change the orientation of device then our activity is recreated and some time we face the NullPointerException. To handle NullPointerException or other exceptions we can save current state and retrive the values or tell in AndroidManifest.xml that don’t destroy this activity.

Solution 1:Tell in AndroidManifest that don’t destroy this activity on orientation change. Just add following android:configChanges in your activity tag.

<activity
  android:name="com.wits.PluginsActivity"
  android:configChanges="mcc|mnc|locale|touchscreen|keyboard|keyboardHidden|navigation|orientation|screenLayout|uiMode|screenSize|smallestScreenSize|fontScale"
>	
</activity>

Solution 2:

If you don’t want to keep continue with android’s default behaviour that is Android re-instatiate our activity and load every thing from start then you can save current activity state (values) and then get that values onCreate or onRestoreInstanceState

We will override onSaveInstanceState to save the values. It calls onSaveInstanceState automatically before destroying the activity.

@Override
public void onSaveInstanceState(Bundle savedInstanceState) {
  super.onSaveInstanceState(savedInstanceState);
  // Save UI state changes to the savedInstanceState.
  savedInstanceState.putBoolean("MyBoolean", true);
  savedInstanceState.putDouble("myDouble", 1.9);
  savedInstanceState.putInt("MyInt", 1);
  savedInstanceState.putString("MyString", "Welcome back to Android");
  // etc.
}

Get these values in onCreate or in onRestoreInstanceState overrided functions

@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");
}

Get these values in onCreate function. I will prefer onCreate function insted of onRestoreInstanceState

@Override
public void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_main)
  
  // Restore UI state from the savedInstanceState.
  // This bundle has also been passed to onCreate.  
  if(savedInstanceState != null)
  {
	  boolean myBoolean = savedInstanceState.getBoolean("MyBoolean");
	  double myDouble = savedInstanceState.getDouble("myDouble");
	  int myInt = savedInstanceState.getInt("MyInt");
	  String myString = savedInstanceState.getString("MyString");
  }
}

 

 

Leave a comment

Your email address will not be published. Required fields are marked *