How to Switch Activity in android and Pass Data between them using Android Studio

Switch Activity Android and Pass Data between them Using New Android Studio:

It is quite common to switch between activities / screens in android. We use different activities / screens in our app for different purposes e.g., to display login screen in one activity and to display login success message in another activity, to display a list of items in one activity and to show the details in another activity when user clicks on one of the list item etc… In this Article, we will discuss about how to switch an Activity in Android using Android Studio and also how to pass data between them.switch_activity

Here, in this example, we will create a subscription form in which user fills in his name and email in the first activity and we will display a thank you note in the second activity mentioning his name and email entered by him in the first activity. Sounds great? Let’s get started!

[widget id=”text-3″]

Before diving into code, let us examine the code we mainly use in this tutorial for switching activities:

Code used to start activity:

We use startActivity() method to start a new activity from the current activity. startActivity takes Intent as its parameter. Intent can be thought as an operation to be performed.

Intent intent = new Intent(Context, Class);
startActivity(intent);

//Example
Intent i = new Intent(this, SecondActivity.class);
startActivity(i);

Here Intent takes two parameters – context and class.

We can also use startActivityForResult() to start a new activity but we use this method if we expect any data to be returned back from our next activity(e.g., taking picture in one activity and send it to another activity).

startActivityForResult(Intent i, int RequestCode);//Takes intent and requestcode
//as parameters. Request code helps identify from which activity you came back
//Example:
Intent i = new Intent(this, NextActivity.class);
startActivityForResult(i,1);// This starts activity and expects result from next
//activity.

@Override
    public void onActivityResult(int requestCode, int resultCode, Intent data)
    {
        if (resultCode == 1) {
            // code to handle the activity with resultcode = 1
        }
    }

 

Code used to send the data to the next activity:

//We use putExtra() method from Intent class to put data into it
i.putExtra(String key, char value);
//Example
//Declaring a key which must be unique
static final String EXTRA_NAME = "com.coderefer.switchactivityandroid.name";
//storing a name
i.putExtra("key", "Vamsi Tallapudi");

 

We store the data to be sent to the next activity in the Intent. To store the data we use the method putExtra() from the Intent class. putExtra() method takes two parameters- key and value pair. This key is required by the activity which wants to get the data from the the previous activity.

Code used to retrieve the data from the previous activity:

//key is needed to retrieve the data
//We pass this key as parameter of getStringExtra()
//Here we are passing EXTRA_NAME declared in the
//previous activity named FirstActivity
name = getIntent().getStringExtra(FirstActivity.EXTRA_NAME);

 

We use getStringExtra() method from Intent class to retrieve the data stored in the Intent. If we want to retrieve a Boolean value we use getBooleanExtra(). They takes key as a parameter. We need to pass the exact key that we used in putExtra() to retrieve the data from the previous activity’s intent.

Switch Activity in Android Using Android Studio:

Prerequisites:

1. How to create Android Studio Project

2. Knowledge on Code snippets discussed above.

The complete code can be downloaded from the link below:

[wpdm_package id=’668′]

 

Creating an XML file:

  1. First we define our xml file for to inflate our first layout which consists of two EditTexts – one for entering name and other to enter our email.
  2. We will also Define Two TextViews above each of the EditTexts to specify what user has to enter in the following EditText fields.
  3. Next we define a Button (In this example I used an ImageButton) so that when user hits that button it takes him to the next activity.

Here is the following XML layout file:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
              android:layout_width="match_parent"
              android:background="@drawable/back"
              android:layout_height="match_parent">
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/sub_heading"
        android:textSize="30dp"
        android:textAlignment="center"
        android:gravity="center"
        android:textStyle="bold"
        android:fontFamily="arial"
        android:textColor="#ffffff"
        android:paddingTop="25dp"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:id="@+id/textView"/>
    <LinearLayout
        android:paddingLeft="20dp"
        android:paddingBottom="50dp"
        android:id = "@+id/linear1"
        android:orientation="vertical"
        android:layout_below="@+id/textView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">
        <TextView
            android:paddingTop="10dp"
            android:layout_width="wrap_content"
            android:textSize="25dp"
            android:textColor="#ffffff"
            android:layout_height="wrap_content"
            android:text="Name"/>
        <EditText
            android:id="@+id/nameET"
            android:paddingTop="10dp"
            android:textColor="#FFFFFF"
            android:layout_width="300dp"
            android:textStyle="italic"
            android:layout_height="wrap_content"
            android:hint="Enter your Name"
            android:textColorHint="#DEDEDE"/>
        <TextView
            android:paddingTop="10dp"
            android:layout_width="wrap_content"
            android:textSize="25dp"
            android:textColor="#ffffff"
            android:layout_height="wrap_content"
            android:text="Email"/>
        <EditText
            android:id="@+id/mailET"
            android:paddingTop="10dp"
            android:textColor="#FFFFFF"
            android:textStyle="italic"
            android:layout_width="300dp"
            android:layout_height="wrap_content"
            android:hint="Enter your Email"
            android:textColorHint="#DEDEDE"/>



    </LinearLayout>

    <ImageButton
        android:layout_below="@+id/linear1"
        android:layout_width="180dp"
        android:padding="40dp"
        android:layout_height="50dp"
        android:src = "@drawable/subscribe"
        android:id="@+id/subscribeButton"
        android:background="@null"
        android:layout_centerVertical="true"
        android:layout_centerHorizontal="true"/>

</RelativeLayout>

 

Next, we define our second layout which consists only of a TextView whose text will be set in our Java Class. The following is the layout for our second activity. Here I named it as activity_second.xml.

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
                xmlns:tools="http://schemas.android.com/tools"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:paddingLeft="@dimen/activity_horizontal_margin"
                android:paddingRight="@dimen/activity_horizontal_margin"
                android:paddingTop="@dimen/activity_vertical_margin"
                android:paddingBottom="@dimen/activity_vertical_margin"
                tools:context="com.coderefer.switchactivityandroid.SecondActivity">

    <TextView
        android:id = "@+id/secText"
        android:textColor="#9A65B2"
        android:textAlignment="center"
        android:text="@string/hello_world"
        android:textSize="25dp"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"/>

</RelativeLayout>

 

We now move on to Java class and start wiring up the EditTexts, and Buttons and also make our activity to do our work. Here I created a new Class by right clicking on PackageName and selecting New > Java Class. I named my first class as FirstActivity.java.

package com.coderefer.switchactivityandroid;

import android.content.Intent;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageButton;


public class FirstActivity extends ActionBarActivity {
    ImageButton subscribeButton;
    EditText name;
    EditText email;
    public static final String EXTRA_NAME = "com.coderefer.switchactivityandroid.name";
    public static final String EXTRA_EMAIL = "com.coderefer.switchactivityandroid.email";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_first);
        subscribeButton = (ImageButton)findViewById(R.id.subscribeButton);
        subscribeButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent i = new Intent(FirstActivity.this, SecondActivity.class);
                name = (EditText)findViewById(R.id.nameET);
                email = (EditText)findViewById(R.id.mailET);
                String ETName = name.getText().toString();
                String ETEmail = email.getText().toString();
                i.putExtra(EXTRA_NAME, ETName);
                i.putExtra(EXTRA_EMAIL, ETEmail);
                startActivity(i);
            }
        });
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }
}

 

Now, in this activity we inflated our activity_first.xml layout and wired up the Buttons and EditTexts. Then we used OnClickListener() method on our subscribe button and we started anonymous class as its parameter.

In our Anonymous class, we stored the data provided by the user such as name and email in the intent by using putExtra() method which takes key and value pair.

We defined two strings EXTRA_NAME, EXTRA_EMAIL  whom we will use as keys in our putExtra() methods.We next passed the intent to startActivity() as its parameter.

startActivity knows which activity to start from the following code:

Intent i = new Intent(FirstActivity.this, SecondActivity.class);

 

Here, Intent() consists of two parameters – Context and Activity which needs to be started next.

Here thus we completed our FirstActivity.java. Make sure you add the reference to Activity in Manifest by using the following code:

 <activity android:name=".FirstActivity"
           android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
</activity>

 

Let us create another activity and name it as SecondActivity.java.

package com.coderefer.switchactivityandroid;

import android.content.Intent;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;


public class SecondActivity extends ActionBarActivity {


    TextView textView;
    private String name;
    private String email;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_second);
        name = getIntent().getStringExtra(FirstActivity.EXTRA_NAME);
        email = getIntent().getStringExtra(FirstActivity.EXTRA_EMAIL);
        textView = (TextView)findViewById(R.id.secText);
        textView.setText("Hello "+ name + ", You have been added to our Subscriber List. You will receive latest updates, tips & tricks to your mail: " + email);

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_second, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }
}

 

We need to access the data we stored in our intent from our FirstActivity. This data is accessed by using the key declared in putExtra method. We retrieve the data by the following code:

String name= getIntent().getStringExtra(FirstActivity.EXTRA_NAME);

Next we set the text of the textview using setText() method. You must reference each new activity in your manifest file. So add the following code in between your manifest’s <application> tag.

<activity
            android:name=".SecondActivity"
            android:label="@string/title_activity_second" >
        </activity>

 

[widget id=”text-3″]

Now we successfully switched activities in android as well as passed the data between them.

[widget id=”text-4″]

Leave a Reply

avatar

This site uses Akismet to reduce spam. Learn how your comment data is processed.

  Subscribe  
Notify of