Send data from one Activity to Another



In the previous article, we saw how to start a new Activity on tap of a button in current Activity. You will come across scenarios wherein you need to send some data from the current Activity to new Activity. In this article, we will learn this topic.

Let us add one text input and a button in current activity. Insert the following code to do so in activity_main.xml file

<EditText
android:id="@+id/edtText"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Enter Text" />

<Button
android:id="@+id/btn"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:onClick="newActivity"
android:text="Send Data" />

In the Java code file, MainActivity.java file of the activity define and initialize the controls added in UI, by adding following code:

EditText editText;
editText = (EditText) findViewById(R.id.edtText);

To send the data from MainActivity to SecondActivity add the event method on button tap.

public void newActivity(View view) {
String msg = editText.getText().toString();
Intent intent = new Intent(MainActivity.this, SecondActivity.class);
intent.putExtra("msg", msg);
startActivity(intent);
}

Here, we are capturing the data in text input on button tap and passing it to the second activity.

Our MainActivity is ready to send data to SecondActivity. Let us create SecondActivity and add a TextView in its graphical UI by adding following code:

<TextView
android:id="@+id/txtView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textAlignment="center"
android:textSize="50dp" />

Initialize the variable for TextView in SecondActivity.java file.

TextView textView;
textView = (TextView) findViewById(R.id.txtView);

In onCreate method add the following code to capture the data sent from the MainActivity on button tap, and display the content in the TextView.

Intent intent = getIntent();
String msg = intent.getStringExtra("msg").toString();
textView.setText(msg);

Now that coding part is complete, let us run this application on an Android device and see it in action. To do so, click on launch button and select the device.

Type any value in the text input and tap on the send button. As we have designed, it will open a new Activity with the content in a label we have passed from MainActivity.

send-data-to-another-activity

This is one of the ways to send data from one Activity to another Activity. You may also use Bundle object for sending data among the Activity.