Sunday 11 January 2015

Android - Passing data from one activity to another using putExtras and getExtras



In this post we will pass data from one activity to another activity using putExtras and getExtras.

Here we have one activity which has an EditText for name another EditText for age a RadioButton for Gender and Spinner for Date Of Birth . We will pass all these values to the other activity.

Lets do it !!


Here we make this android app in AndroidStudio. Get AndroidStudio here

Open a new app, if  you are not familiar with Android Studio ,check my previous post "Setting Up the Project" section .





Open mainactivity.xml













Firstly we design a layout for holding EditTexts,Spinner,RadioGroup with RadioButtons .We will have a LinearLayout with Orientation vertical which is a parent to another four LinearLayouts .

First LinearLayout is for nameIt has one TextView and one EditText , it oriented horizontally

Check the code here,
<LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="horizontal">

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Name"
            android:id="@+id/textView_Name" />


        <EditText
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:inputType="textPersonName"
            android:ems="10"
            android:id="@+id/editText_Name" />
    </LinearLayout>

The second child LinearLayout is for ageIt has one TextView and one EditText , it oriented horizontally

Check the code here,
<LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="horizontal">

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Age"
            android:id="@+id/textView2" />

        <EditText
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:inputType="numberSigned"
            android:ems="10"
            android:id="@+id/editText_Age" />


    </LinearLayout>

The Third child LinearLayout is for genderIt has one Textview and one RadioGroup with two RadioButtons for male and female , it is also oriented horizontally.

Check the code here,
<LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="horizontal">

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Gender"
            android:id="@+id/textView" />

        <RadioGroup
            android:id="@+id/rdg"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:orientation="horizontal">

            <RadioButton
                android:id="@+id/rbmale"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="Male" />

            <RadioButton
                android:id="@+id/rbfemale"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="Female" />
        </RadioGroup>
    </LinearLayout>


The final child LinearLayout is for Date of Birth.It has one TextView and three spinners , each spinner is for day , month and year respectively.To hold those three spinners we will have another horizontal LinearLayout with weights to fit the width.

Check the code here,
<LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="horizontal">

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="D O B :"
            android:id="@+id/textView4" />

        <LinearLayout
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:orientation="horizontal"
            android:weightSum="90">

            <Spinner
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:id="@+id/day"
                android:layout_weight="30"
                android:entries="@array/day" />

            <Spinner
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:id="@+id/month"
                android:layout_weight="30"
                android:entries="@array/month" />

            <Spinner
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:id="@+id/year"
                android:layout_weight="30"
                android:entries="@array/year" />
        </LinearLayout>
    </LinearLayout>

We will have any array of strings for loading  days ,  months and years into those spinners.For this, open strings.xml from the project's  values directory.

















Now create an array of strings for days , months, years
<string-array name="day">
        <item>1</item>
        <item>2</item>
        <item>3</item>
        <item>4</item>
        <item>5</item>
        <item>6</item>
        <item>7</item>
        <item>8</item>
        <item>9</item>
        <item>10</item>
        <item>11</item>
        <item>12</item>
        <item>13</item>
        <item>14</item>
        <item>15</item>
        <item>16</item>
        <item>17</item>
        <item>18</item>
        <item>19</item>
        <item>20</item>
        <item>21</item>
        <item>22</item>
        <item>23</item>
        <item>24</item>
        <item>25</item>
        <item>26</item>
        <item>27</item>
        <item>28</item>
        <item>29</item>
        <item>30</item>
        <item>31</item>
    </string-array>
    <string-array name="month">
        <item>Jan</item>
        <item>Feb</item>
        <item>Mar</item>
        <item>Apr</item>
        <item>May</item>
        <item>June</item>
        <item>July</item>
        <item>Aug</item>
        <item>Sep</item>
        <item>Oct</item>
        <item>Nov</item>
        <item>Dec</item>
    </string-array>
    <string-array name="year">
        <item>1800</item>
        <item>1801-1900</item>
        <item>1901-1990</item>
        <item>1991-2000</item>
        <item>2001-2015</item>
    </string-array>

and finally one button which when clicked passes data to another activity

<Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Go to next Activity"
        android:id="@+id/Show"
        android:layout_gravity="center_horizontal" />


The code for the complete activity_main.xml is :
<LinearLayout 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:orientation="vertical"
    tools:context=".MainActivity">

    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="horizontal">

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Name"
            android:id="@+id/textView_Name" />


        <EditText
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:inputType="textPersonName"
            android:ems="10"
            android:id="@+id/editText_Name" />
    </LinearLayout>


    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="horizontal">

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Age"
            android:id="@+id/textView2" />

        <EditText
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:inputType="numberSigned"
            android:ems="10"
            android:id="@+id/editText_Age" />


    </LinearLayout>

    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="horizontal">

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Gender"
            android:id="@+id/textView" />

        <RadioGroup
            android:id="@+id/rdg"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:orientation="horizontal">

            <RadioButton
                android:id="@+id/rbmale"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="Male" />

            <RadioButton
                android:id="@+id/rbfemale"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="Female" />
        </RadioGroup>
    </LinearLayout>

    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="horizontal">

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="D O B :"
            android:id="@+id/textView4" />

        <LinearLayout
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:orientation="horizontal"
            android:weightSum="90">

            <Spinner
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:id="@+id/day"
                android:layout_weight="30"
                android:entries="@array/day" />

            <Spinner
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:id="@+id/month"
                android:layout_weight="30"
                android:entries="@array/month" />

            <Spinner
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:id="@+id/year"
                android:layout_weight="30"
                android:entries="@array/year" />
        </LinearLayout>
    </LinearLayout>

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Go to next Activity"
        android:id="@+id/Show"
        android:layout_gravity="center_horizontal" />
</LinearLayout>


Now when the data is passed  we need to show that activity , so we will have another layout file called secondactivity,xml which has 4 TextViews for showing name, age, gender ,date of birth.

The code for secondactivity.xml is :
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="center">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/tv_name"
        android:layout_gravity="center_horizontal" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/tv_age" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/tv_gender" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/tv_dob" />

</LinearLayout>

We are done with the design part.
Now lets do the java part(functionality).

Open MainActivity.java










Initialize all the EditTexts,RadioButtons,Spinner,Buttton by using id's which we used in our activity_main.xml.
protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        final EditText et_name = (EditText) findViewById(R.id.editText_Name);
        final EditText et_age = (EditText) findViewById(R.id.editText_Age);
        Button b = (Button) findViewById(R.id.Show);
        day = (Spinner) findViewById(R.id.day);
        month = (Spinner) findViewById(R.id.month);
        year = (Spinner) findViewById(R.id.year);
        RadioGroup gender =(RadioGroup)findViewById(R.id.rdg);
        final RadioButton rbm =(RadioButton)findViewById(R.id.rbmale);
        final RadioButton rbf =(RadioButton)findViewById(R.id.rbfemale);

Now we need to get selected item from RadioGroup as

gender.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                if(checkedId == R.id.rbmale)
                    selectedType = rbm.getText().toString();
                else if(checkedId == R.id.rbfemale)
                    selectedType = rbf.getText().toString();
            }
        });


Now when the button is clicked we will convert all the values of EditText's , RadioButtons,Spinner into strings and passes that data with an intent to SecondActivity with putExtras.

b.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String sp1 = day.getSelectedItem().toString();
                String sp2 = month.getSelectedItem().toString();
                String sp3 = year.getSelectedItem().toString();
                String s = et_name.getText().toString();
                String s1 = et_age.getText().toString();

                Intent ii = new Intent(MainActivity.this, SecondActivity.class);
                ii.putExtra("name", s);
                ii.putExtra("age", s1);
                ii.putExtra("gender",selectedType);
                ii.putExtra("day",sp1);
                ii.putExtra("month",sp2);
                ii.putExtra("year",sp3);


                startActivity(ii);
            }
        });

The complete MainActivity.java code is :


package com.blogspot.codingcorner999.codingcorner_passingdatabetweenactivities;

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.EditText;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Spinner;


public class MainActivity extends ActionBarActivity {
    public Spinner day, month, year;
    private String selectedType = "";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        final EditText et_name = (EditText) findViewById(R.id.editText_Name);
        final EditText et_age = (EditText) findViewById(R.id.editText_Age);
        Button b = (Button) findViewById(R.id.Show);
        day = (Spinner) findViewById(R.id.day);
        month = (Spinner) findViewById(R.id.month);
        year = (Spinner) findViewById(R.id.year);
        RadioGroup gender = (RadioGroup) findViewById(R.id.rdg);
        final RadioButton rbm = (RadioButton) findViewById(R.id.rbmale);
        final RadioButton rbf = (RadioButton) findViewById(R.id.rbfemale);

        gender.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                if (checkedId == R.id.rbmale)
                    selectedType = rbm.getText().toString();
                else if (checkedId == R.id.rbfemale)
                    selectedType = rbf.getText().toString();
            }
        });

        b.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String sp1 = day.getSelectedItem().toString();
                String sp2 = month.getSelectedItem().toString();
                String sp3 = year.getSelectedItem().toString();
                String s = et_name.getText().toString();
                String s1 = et_age.getText().toString();

                Intent ii = new Intent(MainActivity.this, SecondActivity.class);
                ii.putExtra("name", s);
                ii.putExtra("age", s1);
                ii.putExtra("gender", selectedType);
                ii.putExtra("day", sp1);
                ii.putExtra("month", sp2);
                ii.putExtra("year", sp3);


                startActivity(ii);
            }
        });
    }


    @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 create another activity for getting the passed values and name it as SecondActiviy.java(anything you wish). Here we use getExtras for getting the passed values.

The code is here :

package com.blogspot.codingcorner999.codingcorner_passingdatabetweenactivities;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.widget.TextView;

public class SecondActivity extends Activity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.secondactivity);

        TextView t = (TextView) findViewById(R.id.tv_name);
        TextView t1 = (TextView) findViewById(R.id.tv_age);
        TextView t2 = (TextView) findViewById(R.id.tv_gender);
        TextView t3 = (TextView) findViewById(R.id.tv_dob);
        Intent iin = getIntent();
        Bundle b = iin.getExtras();

        if (b != null) {
            String passed_name = (String) b.get("name");
            String passed_age = (String) b.get("age");
            String passed_gender = (String) b.get("gender");
            String passed_day = (String) b.get("day");
            String passed_month = (String) b.get("month");
            String passed_year = (String) b.get("year");
            t.setText("Welcome   " + passed_name);
            t1.setText("You are " + passed_age + "  old");
            t2.setText("Your sex category is : " + passed_gender);
            t3.setText("Your Date of Birth is :  " + passed_month + "/" + passed_day + "/" + passed_year);
        }
    }
}

Now we must add this second activity to the manifest file as the android system must have all the information of the app before running the app. So all the activities , permissions must be included in manifest.xml file.

For adding an activity we write,
<activity
            android:name=".SecondActivity"
            android:label="@string/app_name">
            <intent-filter>
                <action android:name="com.blogspot.codingcorner999.codingcorner_passingdatabetweenactivitiesSecondActivity" />

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

The complete manifest file  looks like,
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.blogspot.codingcorner999.codingcorner_passingdatabetweenactivities">

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

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity
            android:name=".SecondActivity"
            android:label="@string/app_name">
            <intent-filter>
                <action android:name="com.blogspot.codingcorner999.codingcorner_passingdatabetweenactivitiesSecondActivity" />

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

</manifest>

That is it ! we have successfully passed data from one activity to another activity using putExtras and getExtras.

OUTPUT :