How to pass data between Activities on Android application?


This example demonstrates how to pass data between Activities on Android application.

Step 1  − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project.

Step 2  − Add the following code to res/layout/activity_main.xml.

<?xml version="1.0" encoding="utf-8"?>
<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:id="@+id/activity_first"
   android:paddingTop="60dp"
   tools:context=".FirstActivity">
   <LinearLayout
      android:layout_width="fill_parent"
      android:layout_height="wrap_content"
      android:orientation="vertical">
      <LinearLayout
         android:layout_width="fill_parent"
         android:layout_height="wrap_content"
         android:orientation="horizontal"
         android:paddingLeft="10sp">
         <TextView
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="0.25"/>
         <EditText
            android:id="@+id/editTxtName"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="0.75"
            android:ems="10" />
      </LinearLayout>
      <LinearLayout
         android:layout_width="fill_parent"
         android:layout_height="wrap_content"
         android:orientation="horizontal"
         android:paddingLeft="10sp"
         android:paddingTop="16dp">
         <TextView
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="0.25" />
         <Spinner
            android:id="@+id/ageGroupSpinner"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_gravity="center_vertical"
            android:layout_weight="0.75"/>
      </LinearLayout>
      <LinearLayout
         android:layout_width="fill_parent"
         android:layout_height="wrap_content"
         android:orientation="horizontal"
         android:paddingTop="16dp">
         <View
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_weight="0.50" />
         <Button
            android:id="@+id/btnSubmit"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="0.20"/>
      </LinearLayout>
   </LinearLayout>
</RelativeLayout>

Step 3 − Add the following code to res/layout/activity_second.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
   xmlns:android="http://schemas.android.com/apk/res/android"
   android:layout_width="match_parent"
   android:layout_height="match_parent"
   android:id="@+id/activity_second"
   android:paddingTop="60dp">
   <LinearLayout
      android:layout_width="fill_parent"
      android:layout_height="wrap_content"
      android:orientation="vertical">
      <LinearLayout
         android:layout_width="fill_parent"
         android:layout_height="wrap_content"
         android:orientation="horizontal"
         android:paddingLeft="10sp">
         <TextView
            android:id="@+id/displayMsg"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="0.25" />
      </LinearLayout>
   </LinearLayout>
</RelativeLayout>

Step 4  − Add the following code to src/MainActivity.java

package com.example.sample;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.content.Intent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.Toast;
public class FirstActivity extends AppCompatActivity {
   Button btnSubmit = null;
   EditText editTxtName = null;
   private static final String STING_EMPTY = "";
   private static int ageGroup = 0;
   @Override
   protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_first);
      btnSubmit = (Button) findViewById(R.id.btnSubmit);
      btnSubmit.setOnClickListener(new View.OnClickListener() {
         @Override
         public void onClick(View view) {
            editTxtName = (EditText) findViewById(R.id.editTxtName);
            if (STING_EMPTY.equals(editTxtName.getText().toString())) {
               Toast.makeText(FirstActivity.this, "Name Cannot be empty!",
               Toast.LENGTH_LONG).show();
            } else {
               Spinner ageGroupSpinner = (Spinner)findViewById(R.id.ageGroupSpinner);
               ageGroupSpinner.setOnItemSelectedListener(
               new AdapterView.OnItemSelectedListener() {
                  @Override
                  public void onItemSelected(AdapterView<?> adapterView, View view,
                  int i, long l) {
                     //set the corresponding age group when the user changes
                     // the age group from dropdown
                     ageGroup = i;
                  }
                  @Override
                  public void onNothingSelected(AdapterView<?> adapterView) {
                  }
               });
               //Create a new intent for the SecondActivity
               Intent i = new Intent(FirstActivity.this,SecondActivity.class);
               //Populate the input values in a bundle and pass it to SecondActivity
               Bundle b = new Bundle();
               b.putString("name",editTxtName.getText().toString());
               b.putInt("ageGroup",ageGroup);
               //Set the userBundle to the intent
               i.putExtra("userBundle",b);
               startActivity(i);
            }
         }
      });
   }
}

Step 5  − Add the following code to src/SecondActivity.java

package com.example.sample;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.widget.TextView;
public class SecondActivity extends AppCompatActivity {
   @Override
   protected void onCreate(@Nullable Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_second);
      //get the passed intent
      Intent i = getIntent();
      //get the bundle stored inside the intent
      Bundle b = i.getBundleExtra("userBundle");
      TextView displayMsg = (TextView) findViewById(R.id.displayMsg);
      String message = "Hi, " + b.getString("name") + " ";
      int ageGroup = b.getInt("ageGroup");
      switch (ageGroup){
         case 0: message = message + "Enjoy your life";
         break;
         case 1: message = message + "Don't take life too seriously.. Have fun!";
         break;
         case 2: message = message + "Celebrate your life with old memories!";
         break;
      }
      displayMsg.setText(message);
   }
}

Step 6  − Add the following code to Manifests/AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
   package="com.example.sample">
   <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=".FirstActivity">
         <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
         </intent-filter>
      </activity>
      <activity android:name=".SecondActivity"></activity>
   </application>
</manifest>

Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and Click Run  Icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen –

Click here to download the project code.

Updated on: 07-Jul-2020

98 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements