How to pass data between activities in Android Studio

In this article you will learn how to pass data between activities in Android Studio using Java. We will accomplish this with Intents.

"An Intent is a messaging object you can use to request an action from another app component (https://developer.android.com/guide/components/intents-filters)". This will let us bring our data from one activity to another easily.

The finished app will look like this:

How does this app work, you ask? Basically, the app lets you input some value in the input field, then you click on a button to start a new activity using a intent. The intent is grabbing your text with it and transports it to the other activity where it can be picked up and displayed. Amazed? Let's begin.

 

Designing the activities

Let's start by adding the input field and button in the main activity so we have something to play with as soon as possible. Create a new project, choose Empty Activity and locate activity_main.xml in the folder app/res/layout and open it up. Add one EditText and one Button, do this however you want but just make sure you give the items ID's so we can find them from our java sources. If you want to follow me exactly, here's my activity_main.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=".MainActivity">

    <Button
        android:id="@+id/button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_centerHorizontal="true"
        android:layout_marginBottom="208dp"
        android:text="Start second activity" />

    <EditText
        android:id="@+id/editText"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="212dp"
        android:ems="10"
        android:inputType="textPersonName"
        android:hint="Feed me text" />

</RelativeLayout>

While we are at it, why not design the second activity before we dive into the java programming? Right click on the layout folder and choose new -> Layout resource file. I'm going to name mine activity_second.xml. This activity is even skinnier, all that is needed here is a TextView so the text to be transported can be displayed:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textSize="30sp"
        android:layout_centerInParent="true"/>
</RelativeLayout>

I left out the screenshot here because it will just show an empty screen right now. Enough with the design.

 

Programming the main activity

It's time to make our awesome app responsive. Let's bring our focus back to the main activity and then we will create the second activity. Open up MainActivity.java. Take a moment to think about what we want to be done here. We want to type some text, then click on the button to start the second activity. To be able to manipulate the items we need to tell java where to find them, this will be done with the ID's we gave them. Create the two variables in the onCreate function:

final EditText editText = findViewById(R.id.editText);
Button button = findViewById(R.id.button);

If you're not very familiar how buttons work, i encourage you to read my article about buttons here. Now, when the button is clicked, the program should first grab the text from the input field so it can be used for things. This is done in the setOnClickListener's onClick method:

button.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View view) {
        String awesomeText = editText.getText().toString();
    }
});

The text from our EditText is stored in the String awesomeText. The reason why we need .toString(); here, in case you're wondering, is because .getText() only returns an Editable which we need to extract the actual string from. We now have our string, great!

 

Intents

A intent takes two parameters. The first one is Context, and the second one is the activity we want to start, Intent(Context, Class). We have not created the second activity yet, but we will soon. I will name the second activity SecondActivity.java. To start the activity we simply call startActivity(intent);. Before we start the activity though, we need to tell the intent to take our awesomeText with it to the second activity. Intents have a method called putExtra, where you can put different kind of data. putExtra takes two parameters, first one is a key so we can find it, like an ID we used before. The second one is whatever we want to send with it, in this case the String awesomeText. The code will end up like this:

Intent intent = new Intent(MainActivity.this, SecondActivity.class);
intent.putExtra("text", awesomeText);
startActivity(intent);

The intent will give you an error because SecondActivity has not been created yet, we'll fix this in a second, no pun intended.

The final MainActivity.java will look like this:

package com.hallucind.tutorials.passdata;

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 MainActivity extends AppCompatActivity {

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

        final EditText editText = findViewById(R.id.editText);
        Button button = findViewById(R.id.button);

        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String awesomeText = editText.getText().toString();
                Intent intent = new Intent(MainActivity.this, SecondActivity.class);
                intent.putExtra("text", awesomeText);
                startActivity(intent);
            }
        });
    }
}

If you're copying and pasting, don't forget to change the package name.

 

Programming the second activity

Create a new java class by right clicking on the same folder where your MainActivity.java is located and choose new -> Java Class. I will name mine SecondActivity. We make this class an activity by extending AppCompatActivity, just like the MainActivity.java does. We also want the onCreate method that MainActivity.java has. Change your setContentView(R.layout.activity_main); in this class to setContentView(R.layout.activity_second); so we are working with the correct layout:

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

    }
}

When you type extend AppCompatActivity, you will probably get a message saying "The <activity> (package) is not registered in the manifest". Solve this by hover your mouse over SecondActivity and press alt + Enter, choose "Add activity to manifest" and you're good to go.

Like in MainActivity, we connect the TextView here with the ID.

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

We want to display our awesomeText on this TextView. We passed the awesomeText with an intent, so it would be reasonable to get welcome that intent, right? We do this with the following line:

Intent intent = getIntent();

When we passed our String to the intent before, what we actually passed was a Bundle. We get this Bundle from our intent:

Bundle extras = intent.getExtras();

Next, we check if this bundle is null. It shouldn't be, but it's good practice to do so just in case. If it is not equal to null, we get the string by the key we created in the first activity. Then we display this string to the TextView.

if (extras != null) {
    String value = extras.getString("text");
    textView.setText(value);
}

 

Here's the final code for the SecondActivity:

package com.hallucind.tutorials.passdata;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.TextView;

public class SecondActivity extends AppCompatActivity {

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

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

        Intent intent = getIntent();
        Bundle extras = intent.getExtras();

        if (extras != null) {
            String value = extras.getString("text");
            textView.setText(value);
        }
    }
}

 

That's it! Hope you learned something.

Enjoyed this article? Give the teacher an apple.

cookie

1

Author

authors profile photo

Articles with similar tags

Comments