Android | How to send data from one activity to second activity

Pre-requisites:

This article aims to tell and show about how to “Send the data from one activity to second activity using Intent”. In this Example, we have two activities, activity_first which is the source activity and activity_second which is the destination activity. We can send the data using putExtra() method from one activity and get the data from the second activity using getStringExtra() methods.

Example:



In this Example, one EditText is used to input the text. This text is sent to the second activity when the “Send” button is clicked. For this, Intent will start and following methods will run:

  • putExtra() method is use for send the data, data in key value pair key is variable name and value can be Int, String, Float etc.
  • getStringExtra() method is for get the data(key) which is send by above method. according the data type of value there are other methods like getIntExtra(), getFloatExtra()

How to create an Android App to send and receive the data between two activity

  • Step 1: Firstly create a new Android Application. This will create an XML file and a Java File. Please refer the pre-requisites to learn more about this step.

  • Step 2: Open “activity_first_activity.xml” file and add following widgets in a Relative Layout:
    • A EditText to Input the message
    • A Button to send the data

    Also, Assign the ID to each component along with other attributes as shown in the image and the code below. The assigned ID on a component helps that component to be easily found and used in the Java files.
    Syntax:

    android:id="@+id/id_name"

    Here the given IDs are as follows:

    • Send Button: send_button_id
    • input EditText: send_text_id

    This will make the UI of the Application.

  • Step 3: Now, after the UI, this step will create the Backend of the App. For this, open the “first_activity.java” file and instantiate the components made in the XML file (EditText, send Button) using findViewById() method. This method binds the created object to the UI Components with the help of the assigned ID.
    General Syntax:

    ComponentType object = (ComponentType)findViewById(R.id.IdOfTheComponent);

    Syntax for components used:

    Button send_button= (Button)findViewById(R.id.send_button_id);
    send_text = (EditText) findViewById(R.id.send_text_id);


  • Step 4: This step involves setting up the operations on the sending and received the data. These operations are as follows:
    1. first Add the listener on send button and this button will send the data. This is done as follows:

      send_button.setOnClickListener(new View.OnClickListener() {}

      after clicked this button following operation will be performed.

    2. Now create the String type variable for store the value of EditText which is input by user. Get the value and convert it to string. This is done as follows:

      String str = send_text.getText().toString();

    3. Now create the Intent object First_activity.java class to Second_activity class. This is done as follows:

      Intent intent = new Intent(getApplicationContext(), Second_activity.class);

      where getApplicationContext() will fetch the current activity.

    4. Put the value in putExtra method in key value pair then start the activity. This is done as follows:

      intent.putExtra(“message_key”, str);
      startActivity(intent);

      where “str” is the string value and the key is “message_key” this key will use to getting the str value

  • Step 5: Now we have to create a Second_Activity to receive the data.
    The steps to create the second activity is as follows:

    android project > File > new > Activity > Empty Activity

  • Step 6: Now open your second xml file.
    Add TexView for display the receive messages. assign ID to Textview. Second Activity is shown below:


  • Step 7: Now, open up the your second activity java file and perform the following operation.
    1. Define the TextView variable, use findViewById() to get the TextView as shown above.

      receiver_msg = (TextView) findViewById(R.id.received_value_id);

    2. Now In second_activity.java file create the object of getTntent receive the value in String type variable by getStringExtra method using message_key.

      Intent intent = getIntent();
      String str = intent.getStringExtra(“message_key”);

    3. the received value set in the TextView object of second activity xml file

      receiver_msg.setText(str);

  • Step 8: Now Run the app and operate as follows:
    • When the app is opened, it displays a “Input” EditText. Enter the value for the send.
    • click the send button then message will display on second screen.

Below is the complete code for the Application.

activity_first_activity.xml

filter_none

edit
close

play_arrow

link
brightness_4
code

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".first_activity">
  
    <EditText
        android:id="@+id/send_text_id"
        android:layout_width="300dp"
        android:layout_height="wrap_content"
        android:textSize="25dp"
        android:hint="Input"
        android:textStyle="bold"
        android:layout_marginTop="20dp"
        android:layout_marginLeft="40dp"/>
    <Button
        android:id="@+id/send_button_id"
        android:layout_width="wrap_content"
        android:layout_height="40dp"
        android:text="send"
        android:textStyle="bold"
        android:layout_marginTop="150dp"
        android:layout_marginLeft="150dp"/>
  
</RelativeLayout>

chevron_right


First_Activity.java

filter_none

edit
close

play_arrow

link
brightness_4
code

package org.geeksforgeeks.navedmalik.sendthedata;
  
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
  
public class first_activity extends AppCompatActivity {
  
    // define the variable
    Button send_button;
    EditText send_text;
    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_first_activity);
        send_button = (Button)findViewById(R.id.send_button_id);
        send_text = (EditText)findViewById(R.id.send_text_id);
  
        // add the OnClickListener in sender button
        // after clicked this button following Instruction will run
        send_button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v)
            {
  
                // get the value which input by user in EditText
                // and convert it to string
                String str = send_text.getText().toString();
  
                // Create the Intent object of this class Context() to Second_activity class
                Intent intent = new Intent(getApplicationContext(), Second_activity.class);
  
                // now by putExtra method put the value in key, value pair
                // key is message_key by this key we will receive the value, and put the string
  
                intent.putExtra("message_key", str);
  
                // start the Intent
                startActivity(intent);
            }
        });
    }
}

chevron_right


activity_second_activity.xml

filter_none

edit
close

play_arrow

link
brightness_4
code

<?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"
    tools:context="org.geeksforgeeks.navedmalik.sendthedata.Second_activity">
  
    <TextView
        android:id="@+id/received_value_id"
        android:layout_width="300dp"
        android:layout_height="50dp"
        android:textStyle="bold"
        android:textSize="40dp"
        android:layout_marginTop="20dp"
        android:layout_marginLeft="40dp"/>
  
</RelativeLayout>

chevron_right


Second_Activity.java

filter_none

edit
close

play_arrow

link
brightness_4
code

package org.geeksforgeeks.navedmalik.sendthedata;
  
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.TextView;
  
public class Second_activity extends AppCompatActivity {
  
    TextView receiver_msg;
    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_second_activity);
  
        receiver_msg = (TextView)findViewById(R.id.received_value_id);
  
        // create the get Intent object
        Intent intent = getIntent();
  
        // receive the value by getStringExtra() method
        // and key must be same which is send by first activity
        String str = intent.getStringExtra("message_key");
  
        // display the string into textView
        receiver_msg.setText(str);
    }
}

chevron_right


Output:



My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.



Improved By : ManasChhabra2



Article Tags :
Practice Tags :


Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.