Android Activities - Pass Primitives From One Activity To Another.


Let's see how to pass primitive data types from one activity to another. We pass:

  • Strings
  • Integer
  • Boolean(Via CheckBox)

First Activity
First Activity

Second Activity
Second Activity

to a second activity and show them in the second activity.

Gradle Files

We'll add dependencies in the app level build.gradle file.

1. Build.gradle

Here's our app level in the build.gradle file:

    apply plugin: 'com.android.application'

    android {
        compileSdkVersion 24
        buildToolsVersion "25.0.1"

        defaultConfig {
            applicationId "com.tutorials.hp.primitivespassing"
            minSdkVersion 15
            targetSdkVersion 24
            versionCode 1
            versionName "1.0"
        }
        buildTypes {
            release {
                minifyEnabled false
                proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
            }
        }
    }

    dependencies {
        compile fileTree(dir: 'libs', include: ['*.jar'])
        testCompile 'junit:junit:4.12'
        compile 'com.android.support:appcompat-v7:24.2.1'
        compile 'com.android.support:design:24.2.1'
    }

LAYOUT RESOURCES

We have three xml layouts;

  1. activity_main.xml
  2. content_main.xml
  3. activity_second.xml

1. activity_main.xml

  • The template layout for our main activity.
    <?xml version="1.0" encoding="utf-8"?>
    <android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        xmlns:tools="http://schemas.android.com/tools"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:fitsSystemWindows="true"
        tools:context="com.tutorials.hp.primitivespassing.MainActivity">

        <android.support.design.widget.AppBarLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:theme="@style/AppTheme.AppBarOverlay">

            <android.support.v7.widget.Toolbar
                android:id="@+id/toolbar"
                android:layout_width="match_parent"
                android:layout_height="?attr/actionBarSize"
                android:background="?attr/colorPrimary"
                app:popupTheme="@style/AppTheme.PopupOverlay" />

        </android.support.design.widget.AppBarLayout>

        <include layout="@layout/content_main" />

        <android.support.design.widget.FloatingActionButton
            android:id="@+id/fab"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="bottom|end"
            android:layout_margin="@dimen/fab_margin"
            android:src="@android:drawable/ic_dialog_email" />

    </android.support.design.widget.CoordinatorLayout>

2. content_main.xml

  • Let's add our edittexts and checkbox here.
    <?xml version="1.0" encoding="utf-8"?>
    <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        xmlns:tools="http://schemas.android.com/tools"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:paddingBottom="@dimen/activity_vertical_margin"
        android:paddingLeft="@dimen/activity_horizontal_margin"
        android:paddingRight="@dimen/activity_horizontal_margin"
        android:paddingTop="@dimen/activity_vertical_margin"
        app:layout_behavior="@string/appbar_scrolling_view_behavior"
        tools:context="com.tutorials.hp.primitivespassing.MainActivity"
        tools:showIn="@layout/activity_main">

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="vertical">

            <android.support.design.widget.TextInputEditText
                android:id="@+id/nameTxt"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:enabled="true"
                android:focusable="true"
                android:hint="Name"
                android:textSize="25dp"
                android:textStyle="bold" />

            <android.support.design.widget.TextInputEditText
                android:id="@+id/txtID"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:enabled="true"
                android:focusable="true"
                android:hint="ID"
                android:textSize="25dp"
                android:textStyle="bold" />

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:orientation="horizontal"
                android:padding="5dp">

                <TextView
                    android:layout_width="250dp"
                    android:layout_height="wrap_content"
                    android:text="Technology Exists ??"
                    android:textSize="25dp"
                    android:textStyle="bold" />

                <CheckBox
                    android:id="@+id/techExists"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:checked="true"
                    android:textSize="25dp" />
            </LinearLayout>
            <Button android:id="@+id/sendBtn"
                android:layout_width="wrap_content"
                android:layout_height="60dp"
                android:text="Send"
                android:clickable="true"
                android:padding="5dp"
                android:background="#009968"
                android:textColor="@android:color/white"
                android:textStyle="bold"
                android:textSize="20dp" />
        </LinearLayout>
    </RelativeLayout>

3. activity_second.xml

  • Here's the code for the second activity.
  • This activity will receive data from the main activity and show it here.
    <?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:paddingBottom="@dimen/activity_vertical_margin"
        android:paddingLeft="@dimen/activity_horizontal_margin"
        android:paddingRight="@dimen/activity_horizontal_margin"
        android:paddingTop="@dimen/activity_vertical_margin"
        tools:context="com.tutorials.hp.primitivespassing.SecondActivity">

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="vertical">

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:orientation="horizontal"
                android:padding="5dp">

                <TextView
                    android:layout_width="250dp"
                    android:layout_height="wrap_content"
                    android:text="NAME"
                    android:textSize="25dp"
                    android:textStyle="bold" />

                <TextView
                    android:id="@+id/nameTxtSecond"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:text="value received"
                    android:textSize="25dp" />
            </LinearLayout>

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:orientation="horizontal"
                android:padding="5dp">

                <TextView
                    android:layout_width="250dp"
                    android:layout_height="wrap_content"
                    android:text="ID"
                    android:textSize="25dp"
                    android:textStyle="bold" />

                <TextView
                    android:id="@+id/txtIDSecond"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:text="value received"
                    android:textSize="25dp" />
            </LinearLayout>

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:orientation="horizontal"
                android:padding="5dp">

                <TextView
                    android:layout_width="250dp"
                    android:layout_height="wrap_content"
                    android:text="Technology Exists ??"
                    android:textSize="25dp"
                    android:textStyle="bold" />

                <CheckBox
                    android:id="@+id/techExistsSecond"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:checked="true"
                    android:textSize="25dp" />
            </LinearLayout>
        </LinearLayout>
    </RelativeLayout>

JAVA CLASSES

We have two classes or two activities:

  1. MainActivity.java
  2. SecondActivity.java

1. MainActivity class

  • Our MainActivity.
  • We'll pass data from this activity ti the second activity.
    package com.tutorials.hp.primitivespassing;

    import android.content.Intent;
    import android.os.Bundle;
    import android.support.design.widget.FloatingActionButton;
    import android.support.design.widget.TextInputEditText;
    import android.support.v7.app.AppCompatActivity;
    import android.support.v7.widget.Toolbar;
    import android.view.View;
    import android.widget.Button;
    import android.widget.CheckBox;

    public class MainActivity extends AppCompatActivity {

        //DECLARE VIEWS
        private TextInputEditText txtName, txtID;
        private CheckBox chkTechnologyExists;
        private Button sendBtn;

        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
            Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
            setSupportActionBar(toolbar);

            this.initializeViews();

            FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
            fab.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                }
            });

            //WHEN SEND BTN IS CLICKED,SEND
            sendBtn.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    sendData();
                }
            });
        }

        /*
        REFERENCE VIEWS WE ARE USING
         */
        private void initializeViews() {
            txtName = (TextInputEditText) findViewById(R.id.nameTxt);
            txtID = (TextInputEditText) findViewById(R.id.txtID);
            chkTechnologyExists = (CheckBox) findViewById(R.id.techExists);
            sendBtn = (Button) findViewById(R.id.sendBtn);

        }

        /*
        SEND DATA TO SECOND ACTIVITY
         */
        private void sendData() {
            //GET PRIMITIVE VALUES TO SEND
            String name = txtName.getText().toString();
            int id = Integer.parseInt(txtID.getText().toString());
            Boolean techExists = chkTechnologyExists.isChecked();

            //PACK THEM IN AN INTENT OBJECT
            Intent i = new Intent(this, SecondActivity.class);
            i.putExtra("NAME_KEY", name);
            i.putExtra("ID_KEY", id);
            i.putExtra("TECHEXISTS_KEY", techExists);

            //LETS LEAVE OUR TXTS CLEARED
            txtName.setText("");
            txtID.setText("");

            //START SECOND ACTIVITY
            this.startActivity(i);
        }
    }

2. Second Activity class

  • Our second activity.
  • Will receive data from main activity and show them in textviews and checkbox.
    package com.tutorials.hp.primitivespassing;

    import android.support.design.widget.TextInputEditText;
    import android.support.v7.app.AppCompatActivity;
    import android.os.Bundle;
    import android.widget.CheckBox;
    import android.widget.Spinner;
    import android.widget.TextView;
    import android.widget.Toast;

    public class SecondActivity extends AppCompatActivity {

        //DECALRE SECOND ACTIVITY VIEWS
        TextView txtName2;
        TextView txtID2;
        CheckBox chkTechnologyExists2;

        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_second);

            //INITIALIZE THESE VIEWS
            txtName2 = (TextView) findViewById(R.id.nameTxtSecond);
            txtID2 = (TextView) findViewById(R.id.txtIDSecond);
            chkTechnologyExists2 = (CheckBox) findViewById(R.id.techExistsSecond);

            //RECEIVE DATA FROM MAIN ACTIVITY
            String name = getIntent().getStringExtra("NAME_KEY");
            int id = getIntent().getIntExtra("ID_KEY", 0);
            Boolean techExists = getIntent().getBooleanExtra("TECHEXISTS_KEY", false);

            //SHOW A TOAST
            Toast.makeText(SecondActivity.this, name, Toast.LENGTH_LONG).show();

            //SET THE DATA TO OUR LOCAL VIEWS
            txtName2.setText(name);
            txtID2.setText(String.valueOf(id));
            chkTechnologyExists2.setChecked(techExists);
        }
    }

How do You Feel after reading this?

According to scientists, we humans have 8 primary innate emotions: joy, acceptance, fear, surprise, sadness, disgust, anger, and anticipation. Feel free to tell us how you feel about this article using these emotes or via the comment section. This feedback helps us gauge our progress.

Help me Grow.

I set myself some growth ambitions I desire to achieve by this year's end regarding this website and my youtube channel. Am halfway. Help me reach them by:




Recommendations


What do You Think


Previous Post Next Post