How to pass data to another activity in Android Android 20.07.2016

Following is a simple example how to pass data from one activity to another activity in Android. As bonus, we'll track how much user click on button (methods onSaveInstanceState() and onRestoreInstanceState()) and save state of main activity between starts (SharedPreferences).

The main object for message passing is intent object. As a message object, it's purpose is to communicate with other components of the application. I'll show you how to pass information with the intent and how to get it out again.

I'll add an EditText element to the main activity so that we have something to send to SecondActivity. I'll use the TextView view to display the message.

Also, you'll see how to handle the onSaveInstanceState() and onRestoreInstanceState() callbacks to save your application's state.

// MainActivity.java
import android.content.Intent;
import android.content.SharedPreferences;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {
    public static final String REQUEST_RESULT="REQUEST_RESULT";
    private static final String KEY_PASSED = "PASSED";
    private static final String KEY_TEXT = "TEXT";
    private int passed = 0;
    TextView tvPassed;
    EditText etNumber;

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

        tvPassed = (TextView)findViewById(R.id.tvPassed);
        etNumber = (EditText) findViewById(R.id.etNumber);

        SharedPreferences settings = getPreferences(MODE_PRIVATE);

        if (savedInstanceState!=null) {
            passed = savedInstanceState.getInt(KEY_PASSED);
        } else {
            passed = settings.getInt(KEY_PASSED, 0);
            etNumber.setText(settings.getString(KEY_TEXT, ""));
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        tvPassed.setText("Clicked " + Integer.toString(passed));
    }

    @Override
    protected void onPause() {
        super.onPause();
        SharedPreferences settings = getPreferences(MODE_PRIVATE);
        SharedPreferences.Editor ed = settings.edit();
        ed.putInt(KEY_PASSED, passed);
        ed.putString(KEY_TEXT, etNumber.getText().toString());
        ed.commit();
    }

    public void onPassData(View v) {
        passed += 1;

        String text = etNumber.getText().toString();
        Intent i = new Intent(this, SecondActivity.class);
        i.putExtra(Intent.EXTRA_TEXT, text);
        //startActivity(i);
        startActivityForResult(i, 1);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            Toast.makeText(getApplicationContext(), data.getStringExtra(REQUEST_RESULT), Toast.LENGTH_LONG).show();
        }
    }

    @Override
    protected void onSaveInstanceState(Bundle state) {
        super.onSaveInstanceState(state);
        state.putInt(KEY_PASSED, passed);
    }

    @Override
    protected void onRestoreInstanceState(Bundle state) {
        super.onRestoreInstanceState(state);
        passed = state.getInt(KEY_PASSED);
    }
}

As expected, the intent object is doing all the work. I created an intent and then added some extra data. The second activity was launched with the intent, so it's simply a matter of getting the intent and checking for the data sent along with it. We do this in onCreate().

Returning a result from an activity is not very different from the way we just called the activity in the previous snippet.

// SecondActivity.java
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;

public class SecondActivity extends AppCompatActivity {

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

        TextView tv = (TextView)findViewById(R.id.tvNumber);
        if (getIntent() != null && getIntent().hasExtra(Intent.EXTRA_TEXT)) {
            tv.setText(getIntent().getStringExtra(Intent.EXTRA_TEXT));
        }
    }

    public void onBack(View v) {
        Intent i = new Intent();
        i.putExtra(MainActivity.REQUEST_RESULT, "Hello from Second activity!");
        setResult(RESULT_OK, i);
        finish();
    }
}

As you can see, getting the results back is relatively straightforward. We just call the intent with startActivityForResult, so it knows that we want a result. We set up the onActivityResult() callback handler to receive the results. Finally, we make sure that the second activity returns a result with setResult() before closing the activity. Also, it's good practice to check the result code to make sure that the user didn't cancel the action.

Layout for MainActivity

# 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"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.example.proft.passdata.MainActivity">

    <EditText
        android:id="@+id/etNumber"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:hint="Your number"/>

    <Button
        android:id="@+id/btnPass"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Pass"
        android:onClick="onPassData"
        android:layout_below="@id/etNumber"
        android:layout_centerHorizontal="true"
        />

    <TextView
        android:id="@+id/tvPassed"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_centerHorizontal="true" />
</RelativeLayout>

Layout for SecondActivity

# activity_second.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"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.example.proft.passdata.SecondActivity">

    <TextView
        android:id="@+id/tvNumber"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"/>

    <Button
        android:id="@+id/btnBack"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Back"
        android:onClick="onBack"
        android:layout_below="@id/tvNumber"
        android:layout_centerHorizontal="true"
        />
</RelativeLayout>

Result

android_pass_activity.png