In Android User Interface is displayed through an activity. In Android app development you might face situations where you need to switch between one Activity (Screen/View) to another. In this tutorial I will be discussing about switching between one Activity to another and sending data between activities.

Before getting into complete tutorial I am giving the code snippets for handling activities. Lets assume that our new Activity class name is SecondScreen.java

Opening new Activity To open new activity following startActivity()  or startActivityForResult() method will be used.

Intent i = new Intent(getApplicationContext(), SecondScreen.class);
StartActivity(i);

Sending parameters to new Activity

To send parameter to newly created activity putExtra() methos will be used.

i.putExtra("key", "value");

// Example of sending email to next screen as
// Key = 'email'
// value = 'myemail@gmail.com'
i.putExtra("email", "myemail@gmail.com");

Receiving parameters on new Activity

To receive parameters on newly created activity getStringExtra() method will be used.

Intent i = getIntent();
i.getStringExtra("key");

// Example of receiving parameter having key value as 'email'
// and storing the value in a variable named myemail
String myemail = i.getStringExtra("email");

Opening new Activity and expecting result

In some situations you might expect some data back from newly created activity. In that situations startActivityForResult() method is useful. And once new activity is closed you should you use onActivityResult() method to read the returned result.

Intent i = new Intent(getApplicationContext(), SecondScreen.class);
startActivityForResult(i, 100); // 100 is some code to identify the returning result

// Function to read the result from newly created activity
@Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
              super.onActivityResult(requestCode, resultCode, data);
             if(resultCode == 100){

            // Storing result in a variable called myvar
            // get("website") 'website' is the key value result data
           String mywebsite = data.getExtras().get("result");
       }
}

Sending result back to old activity when StartActivityForResult() is used

Intent i = new Intent();
// Sending param key as 'website' and value as 'androidhive.info'
i.putExtra("website", "AndroidHive.info");

// Setting resultCode to 100 to identify on old activity
setResult(100,in);

Closing Activity

To close activity call finish() method

finish();

Add entry in AndroidManifest.xml

To run our application you should enter your new activity in AndroidManifest.xml file. Add new activity between <application> tags

<activity android:name=".NewActivityClassName"></activity>

Let’s Start with a simple project.

So now we have all the code snippets related to activities. In this tutorial i created two xml layouts(screen1.xmlscreen2.xml) and two Activities FirstScreenActivity.java, SecondScreenActivity.java.

The following diagram will give you an idea about the file structure you will be need in this tutorial.

Directory Structure

Now lets start by creating a simple project.

1. Create a new project File -> New ->New Project. While creating a new project give activity name as FirstScreenActivity.
2. Now you need to create user interface for the FirstScreenActivity.java.
3. Create a new xml file in layout folder or rename the activity_main.xml to screen1.xml.
4. Now insert the following code in screen1.xml to design a small layout. This layout contains simple form with a button.

screen1.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:padding="20dp"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">

    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="Name: "/>

    <EditText
        android:id="@+id/name"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_marginBottom="10dip"/>

    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="Email: " />

    <EditText
        android:id="@+id/email"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_marginBottom="10dip"/>

    <Button
        android:id="@+id/btnNextScreen"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="Send to Next Screen"
        android:layout_marginTop="15dip"/>
</LinearLayout>

Screen 1 Output

 

5. Now open your FirstScreenActivity.java and Type the following code. In the following code we are creating a new Intent and passing parameters on clicking button.

FirstScreenActivity.java

package com.codedecode.yashpwr;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

public class FirstScreenActivity extends Activity {
    // Initializing variables
    EditText inputName;
    EditText inputEmail;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.screen1);

        inputName = (EditText) findViewById(R.id.name);
        inputEmail = (EditText) findViewById(R.id.email);
        Button btnNextScreen = (Button) findViewById(R.id.btnNextScreen);

        //Listening to button event
        btnNextScreen.setOnClickListener(new View.OnClickListener() {

            public void onClick(View arg0) {
                //Starting a new Intent
                Intent nextScreen = new Intent(getApplicationContext(), SecondScreenActivity.class);

                //Sending data to another Activity
                nextScreen.putExtra("name", inputName.getText().toString());
                nextScreen.putExtra("email", inputEmail.getText().toString());

                Log.e("n", inputName.getText()+"."+ inputEmail.getText());

                startActivity(nextScreen);

            }
        });
    }
}

6. Create a class called SecondScreenActivity.java.

7. Now we need interface for our Second Actvity. Create a new xml file and name it as screen2.xml.

screen2.xml.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:padding="20dp"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="Your Screen 1 Values"
        android:textSize="25dip"
        android:gravity="center"
        android:layout_margin="15dip"/>

    <TextView
        android:id="@+id/txtName"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_margin="15dip"
        android:textSize="18dip"/>

    <TextView
        android:id="@+id/txtEmail"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_margin="15dip"
        android:textSize="18dip"/>

    <Button
        android:id="@+id/btnClose"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="15dip"
        android:text="Close"/>

</LinearLayout>

8. Now open SecondScreenActivity.java and type the following code. Here we are simply reading the parameters and displaying them on to screen.

SecondScreenActivity.java

package com.codedecode.yashpwr;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

public class SecondScreenActivity extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.screen2);

        TextView txtName = (TextView) findViewById(R.id.txtName);
        TextView txtEmail = (TextView) findViewById(R.id.txtEmail);
        Button btnClose = (Button) findViewById(R.id.btnClose);

        Intent i = getIntent();
        // Receiving the Data
        String name = i.getStringExtra("name");
        String email = i.getStringExtra("email");
        Log.e("Second Screen", name + "." + email);

        // Displaying Received data
        txtName.setText(name);
        txtEmail.setText(email);

        // Binding Click event to Button
        btnClose.setOnClickListener(new View.OnClickListener() {

            public void onClick(View arg0) {
                //Closing SecondScreen Activity
                finish();
            }
        });

    }
}

9. Now everything is ready and before running your project make sure that you an entry of new activity name in AndroidManifest.xml file. Open you AndroidManifest.xml file and modify the code as below.

AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.codedecode.yashpwr">

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".FirstScreenActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity android:name=".SecondScreenActivity"></activity>
    </application>

</manifest>

10. Finally run your project. You can see the application is running by switching between screens.

Screen 2 | Final Output

 

Download Code

Happy Coding ūüôā