Thursday, December 26, 2024
Google search engine
HomeLanguagesJavaHow to Send Data From One Activity to Second Activity in Android?

How to Send Data From One Activity to Second Activity in Android?

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

Pre-requisites:

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 the following methods will run:

  • putExtra() method is used for sending the data, data in key-value pair key is variable name and value can be Int, String, Float, etc.
  • getStringExtra() method is for getting the data(key) that is sent by the above method. According to 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 by Step Implementation

Step 1: Create a New Project in Android Studio

To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. The code for that has been given in both Java and Kotlin Programming Language for Android. This will create an XML file and a Java File. Please refer to the prerequisites to learn more about this step.

Step 2: Working with the XML Files

Next, go to the activity_main.xml file, which represents the UI of the project. Below is the code for the activity_main.xml file. Comments are added inside the code to understand the code in more detail. Open the “activity_first_activity.xml” file and add the following widgets in a Relative Layout.

  • An 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/Kotlin files.

Syntax:

android:id="@+id/id_name"

Here the given IDs are as follows:

  • Send Button: send_button_id
  • input EditText: send_text_id

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"
    tools:context=".first_activity">
  
    <EditText
        android:id="@+id/send_text_id"
        android:layout_width="300dp"
        android:layout_height="wrap_content"
        android:layout_marginLeft="40dp"
        android:layout_marginTop="20dp"
        android:hint="Input"
        android:textSize="25dp"
        android:textStyle="bold" />
  
    <Button
        android:id="@+id/send_button_id"
        android:layout_width="wrap_content"
        android:layout_height="40dp"
        android:layout_marginLeft="150dp"
        android:layout_marginTop="150dp"
        android:text="send"
        android:textStyle="bold" />
</RelativeLayout>


This will make the UI of the Application

Step 3: Working with the MainActivity File

Go to the MainActivity File and refer to the following code. Below is the code for the MainActivity File. Comments are added inside the code to understand the code in more detail. Now, after the UI, this step will create the Backend of the App. For this, open the “first_activity” 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. 

Syntax: General  

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

Syntax: for components used is as follows:

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

Setting up the Operations for the Sending and Receiving of Data.

These Operations are as follows: 

Add the listener to the send button and this button will send the data.

This is done as follows:

send_button.setOnClickListener(v -> {} 

after clicking this button following operation will be performed. Now create the String type variable to store the value of EditText which is input by the user. Get the value and convert it to a string.

This is done as follows: 

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

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. Put the value in the putExtra method in the 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 get the str value 

Java




import android.content.Intent;
import android.os.Bundle;
import android.widget.Button;
import android.widget.EditText;
import androidx.appcompat.app.AppCompatActivity;
  
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 = findViewById(R.id.send_button_id);
        send_text = findViewById(R.id.send_text_id);
  
        // add the OnClickListener in sender button after clicked this button following Instruction will run
        send_button.setOnClickListener(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);
        });
    }
}


Kotlin




import android.content.Intent
import android.os.Bundle
import android.widget.Button
import android.widget.EditText
import androidx.appcompat.app.AppCompatActivity
  
class first_activity : AppCompatActivity() {
      
    // define the variable
    lateinit var send_button: Button
    lateinit var send_text: EditText
  
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_first_activity)
          
        send_button = findViewById(R.id.send_button_id)
        send_text = findViewById(R.id.send_text_id)
  
        // add the OnClickListener in sender button after clicked this button following Instruction will run
        send_button.setOnClickListener {
            // get the value which input by user in EditText and convert it to string
            val str = send_text.text.toString()
            // Create the Intent object of this class Context() to Second_activity class
            val intent = Intent(applicationContext, Second_activity::class.java)
            // 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)
        }
    }
}


Step 4: Creating Second_Activity to Receive the Data. 

The steps to create the second activity are as follows:

android project > File > new > Activity > Empty Activity 

Step 5: Working with the Second XML File

Add TextView to display the received messages. assign an ID to Textview.

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


The Second Activity is shown below:

Step 6: Working with the SecondActivity File

Define the TextView variable, use findViewById() to get the TextView as shown above. 

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

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

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

The received value set in the TextView object of the second activity XML file

receiver_msg.setText(str);

Java




import android.content.Intent;
import android.os.Bundle;
import android.widget.TextView;
import androidx.appcompat.app.AppCompatActivity;
  
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 = 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);
    }
}


Kotlin




import android.os.Bundle
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
  
class Second_activity : AppCompatActivity() {
      
    lateinit var receiver_msg: TextView
  
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_second_activity)
          
        receiver_msg = findViewById(R.id.received_value_id)
        // create the get Intent object
        val intent = intent
        // receive the value by getStringExtra() method and
        // key must be same which is send by first activity
        val str = intent.getStringExtra("message_key")
        // display the string into textView
        receiver_msg.text = str
    }
}


Output:

Dominic Rubhabha-Wardslaus
Dominic Rubhabha-Wardslaushttp://wardslaus.com
infosec,malicious & dos attacks generator, boot rom exploit philanthropist , wild hacker , game developer,
RELATED ARTICLES

Most Popular

Recent Comments