Passing data between activities

We’ve seen how to respond to a button click, and how to transition to a new activity. On this page, we’ll also pass a piece of data to the new activity, using the Intent object. Below is an illustration of what we want to accomplish.

User enters their name, clicks button, then switches to a personalized greeting

User enters their name, clicks button, then switches to a personalized greeting

There are two activities: the first two screens are both MainActivity, and the third screen is SecondActivity. The user enters their name in the MainActivity and then we want to print their name in the SecondActivity.

So, in the onClick method of the OnClickListener for the button, we need grab the string from the EditText field, and then use intent.putExtra to store it in the intent.

    Intent intent = new Intent(getActivity(), SecondActivity.class);
    EditText nameText = (EditText) rootView.findViewById(R.id.yourName);
    intent.putExtra("yourName", nameText.getText().toString());
    startActivity(intent);
Note: When we use getActivity() as above, I’m assuming we’re inside a Fragment class – this will usually be the case in Activities generated by Android Studio. If you’re using Eclipse however, you’re probably coding directly in the Activity class because there is no Fragment. Therefore, you can usually replace getActivity() with this or perhaps with MainActivity.this.

Then when we arrive in the SecondActivity (actually, this is in the nested PlaceholderFragment, in its onCreateView method), we can ask the incoming Intent object for the string using the same ‘key’ – in this case, "yourName".

    String yourName = getActivity().getIntent().getStringExtra("yourName");
    TextView greeting = (TextView)rootView.findViewById(R.id.greetingText);
    greeting.setText("Welcome to our app, " + yourName);
Note: Same caveat as above, about getActivity().

Below I will embed the complete class definition for each Activity, so you can see everything in context.

MainActivity

package com.example.app;

import android.content.Intent;
import android.support.v7.app.ActionBarActivity;
import android.support.v4.app.Fragment;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.TextView;

public class MainActivity extends ActionBarActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Log.i("LogTest", "We have called onCreate!");
        setContentView(R.layout.activity_main);

        if (savedInstanceState == null) {
            getSupportFragmentManager().beginTransaction()
                    .add(R.id.container, new PlaceholderFragment())
                    .commit();
        }

    }

    @Override
    protected void onResume() {
        super.onResume();
        Log.i("LogTest", "We have called onResume!");
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.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();
        if (id == R.id.action_settings) {
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    /**
     * A placeholder fragment containing a simple view.
     */
    public static class PlaceholderFragment extends Fragment {

        public PlaceholderFragment() {
        }

        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                Bundle savedInstanceState) {
            final View rootView = inflater.inflate(R.layout.fragment_main, container, false);
            Button clickMe = (Button) rootView.findViewById(R.id.clickMe);
            final TextView helloText = (TextView) rootView.findViewById(R.id.helloText);
            Log.i("LogTest", "clickMe is " + clickMe);
            clickMe.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    // Turn on the spinner
                    ProgressBar progress = (ProgressBar)rootView.findViewById(R.id.progressBar);
                    progress.setVisibility(View.VISIBLE);
                    // Update the log and a text view.
                    Log.i("LogTest", "You clicked the button!");
                    helloText.setText("Thanks for clicking.");
                    // Transition to SecondActivity
                    Intent intent = new Intent(getActivity(), SecondActivity.class);
                    // Get the name from the EditText component
                    EditText nameText = (EditText) rootView.findViewById(R.id.yourName);
                    intent.putExtra("yourName", nameText.getText().toString());
                    startActivity(intent);
                }
            });
            return rootView;
        }
    }

}

SecondActivity

package com.example.app;

import android.support.v7.app.ActionBarActivity;
import android.support.v4.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

public class SecondActivity extends ActionBarActivity {

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

        if (savedInstanceState == null) {
            getSupportFragmentManager().beginTransaction()
                    .add(R.id.container, new PlaceholderFragment())
                    .commit();
        }
    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.second, 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();
        if (id == R.id.action_settings) {
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    /**
     * A placeholder fragment containing a simple view.
     */
    public static class PlaceholderFragment extends Fragment {

        public PlaceholderFragment() {
        }

        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                Bundle savedInstanceState) {
            View rootView = inflater.inflate(R.layout.fragment_second, container, false);
            String fullName = getActivity().getIntent().getStringExtra("yourName");
            TextView greeting = (TextView)rootView.findViewById(R.id.greetingText);
            greeting.setText("Welcome to our app, " + fullName);
            return rootView;
        }
    }

}

fragment_main.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:paddingBottom="@dimen/activity_vertical_margin"
    tools:context="com.example.app.MainActivity$PlaceholderFragment">

    <TextView
        android:text="@string/hello_world"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/helloText">
    </TextView>
    <LinearLayout
            android:orientation="horizontal"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center">
        <ImageView
                android:src="@drawable/youtube"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_gravity="center_vertical"/>
        <Button android:text="Click me please"
                android:layout_width="wrap_content"
                   android:layout_height="wrap_content"
                   android:layout_gravity="center_vertical"
                   android:layout_marginLeft="15px"
                   android:id="@+id/clickMe"/>
    </LinearLayout>

    <EditText
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:id="@+id/yourName"
            android:hint="Your name"/>

    <ProgressBar
            style="?android:attr/progressBarStyleLarge"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@+id/progressBar"
            android:visibility="invisible"/>

</LinearLayout>