How would you save Activity state during a screen rotation?

When your orientation changes, you don’t have to manually change to the landscape layout file. Android does this automatically for you. When orientation changes, Android destroys your current activity and creates a new activity again, this is why you are losing the text.

Basically, whenever Android destroys and recreates your Activity for orientation change, it calls onSaveInstanceState() before destroying and calls onCreate() after recreating. Whatever you save in the bundle in onSaveInstanceState, you can get back from the onCreate() parameter.

private TextView mTextView;
private static final String KEY_TEXT_VALUE = "textValue";
protected void onCreate(Bundle savedInstanceState) {
  mTextView = (TextView) findViewById(;
  if (savedInstanceState != null) {
      CharSequence savedText = savedInstanceState.getCharSequence(KEY_TEXT_VALUE);

protected void onSaveInstanceState (Bundle outState) {
   outState.putCharSequence(KEY_TEXT_VALUE, mTextView.getText());


When you choose Fragment over Activity?

  • Activities are designed to represent a single screen of my application, while
  • Fragments are designed to be reusable UI layouts with logic embedded inside of them

Google advises you to always use Fragments. In the simplest case, Fragments are used like containers of activities. Android 4 (ICS) supports both Smartphones and Tablets. This means the same application will be running on a smartphone and a tablet and they are likely to be very different.

Historically each screen in an Android app was implemented as a separate Activity. This creates a challenge in passing information between screens because the Android Intent mechanism does not allow passing a reference type (i.e. object) directly between Activities. By making each screen a separate Fragment, this data passing headache is completely avoided. Fragments always exist within the context of a given Activity and can always access that Activity. By storing the information of interest within the Activity, the Fragment for each screen can simply access the object reference through the Activity.

How to pass data between Activities in Android?

Consider a scenario after login activity , Sign-out button visible in each activity , now we need to keep session ID available of all activities !!


The easiest way to do this would be to pass the session id to the signout activity in the Intent you’re using to
start the activity:

Intent intent = new Intent(getBaseContext(), SignoutActivity.class);
intent.putExtra("EXTRA_SESSION_ID", sessionId);

Access that intent on next activity:

String sessionId = getIntent().getStringExtra("EXTRA_SESSION_ID");