onCreate(Bundle savedInstanceState) Activity Function And Example In Android

onCreate(Bundle savedInstanceState) Function in Android:

  • When an Activity first call or launched then onCreate(Bundle savedInstanceState) method is responsible to create the activity.
  • When ever orientation(i.e. from horizontal to vertical or vertical to horizontal) of activity gets changed or when an Activity gets forcefully terminated by any Operating System then savedInstanceState i.e. object of Bundle Class will save the state of an Activity.
  • After Orientation changed then onCreate(Bundle savedInstanceState) will call and recreate the activity and load all data from savedInstanceState.
  • Basically Bundle class is used to stored the data of activity whenever above condition occur in app.
  • onCreate() is not required for apps. But the reason it is used in app is because that method is the best place to put initialization code.
  • You could also put your initialization code in onStart() or onResume() and when you app will load first, it will work same as in onCreate().

Example of onCreate(Bundle savedInstanceState):

Lets create a simple program to understand onCreate(Bundle savedInstanceState) more deeply.

In the below example we will ask the user to Enter the name, save his name in Bundle object and then display the same name when user rotates the screen.

First create a new project, name it Exampleoncreate and create a activity name MainActivity. Also create a content_main.xml in layout if not present by default.

For designing UI we will create 3 things in content_main.xml:

  • We have used Linear Layout
  • a TextView to display basic detail about the program to user,
  • EditText where user will enter the name which will be save in Bundle object
  • a TextView which will display the name on screen rotation

Below is the complete code of content_main.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent" >

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceMedium"
        android:text="Fill Name Then Rotate:"
        android:id="@+id/textView2" />


    <!-- used to enter the data and get saved in bundle-->

    <EditText
        android:id="@+id/editText"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:inputType="text"

        />


    <!-- retrived data shown in this textview -->

    <TextView

        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        />



</LinearLayout>

Now go to MainActivity.java and paste the below code. The explanation is given using comments in the code itself.

import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.EditText;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {

    private static String TAG = "ActivityName";
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.content_main);
    }

//Saving The Text Entered by User

    protected void onSaveInstanceState(Bundle outState)
    {
        super.onSaveInstanceState(outState);
        Log.i(TAG, "onSaveInstanceState");

        final EditText editText=
                (EditText) findViewById(R.id.editText);// getting the reference of editext from xml
        CharSequence text  = editText.getText();// getting text u entered in edittext
        outState.putCharSequence("savedText", text);// saved that text in bundle object i.e. outState

    }

//Restoring the State

    @Override
    protected void onRestoreInstanceState(Bundle savedInstanceState)
    {
        super.onRestoreInstanceState(savedInstanceState);
        Log.i(TAG, "onRestoreInstanceState");
        final TextView textView =
                (TextView) findViewById(R.id.textView);// getting the reference of textview from xml

        CharSequence savedText=
                savedInstanceState.getCharSequence("savedText");// getting the text of editext

        textView.setText(savedText);// set the text that is retrieved from bundle object
    }

}

Make sure MainActivity is mentioned in Manifest file. Below is the code of AndroidManifest.xml

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="abhiandroid.com.exampleoncreate">

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity
            android:name=".MainActivity"
            android:label="@string/app_name"
            android:theme="@style/AppTheme.NoActionBar">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

Output:

Now run the application in Emulator and enter the name. In our case we have entered AbhiAndroid.

Fill name in oncreate example

Now rotate the screen from vertical to horizontal (Press ctrl + F12 in Windows & Fn+Left CTRL+F12 on Mac to rotate). After you change screen orientation you will see the same name appear just right side of name.

Output change on screen orientation

So we have retrieved the data from Bundle object.

3 thoughts on “onCreate(Bundle savedInstanceState) Activity Function And Example In Android”