Passing Data Between Activities Android Tutorial

Transfer data between different activity is a common use case in android application. This example will tell you how to use Intent to transfer data to another activity and how to get response result data from other activity.

1. Passing Data Between Activity Overview.

  1. This example contains two activity, source activity and target activity.
  2. There are two button in source activity and one button in target activity.
  3. Click the first button will transfer data to target activity. But when click return button in target activity, it can not get response result data.
    passing data between activities without response data android tutorial
  4. Click the second button will transfer data to target activity also, and when click return button or click Back menu at the bottom in target activity, it can get the response result data from target activity and display.
    passing data between activities with response data android tutorial

2. Passing Data To Other Activity Using Intent.

  1. Create a New Explicit or Implicit Intent object in source activity.
  2. Call intent.putExtra(String key, Object data) method to save data in it.
  3. Call startActivity(intent) method in source activity to pass the intent to android os.
  4. Call getIntent() method in target activity.
  5. Use intent.getStringExtra(String key) to get the transferred data.

3. Get Response Result Data Back From Target Activity.

  1. Create a New Explicit or Implicit Intent object in source activity.
  2. Call intent.putExtra(String key, Object data) method to save data in it.
  3. Call startActivityForResult(Intent intent, int requestCode) method in source activity to pass the intent to android os.
  4. Create a new Intent object in target activity.
  5. Use intent.putExtra(String key, Object data) to set return result data in the intent.
  6. Invoke setResult(RESULT_OK, intent) to set the return intent in android os. The first parameter can be android.app.Activity.RESULT_OK or RESULT_CANCELED.
  7. In source activity java class, override onActivityResult(int requestCode, int resultCode, Intent dataIntent) to get the returned intent and saved response result data.
READ :   Android Activity Best Practice

4. Transfer Data Between Activity Example Source Code.

4.1 Source Activity Layout Xml File.

activity_passing_data_source.xml

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical">

    <Button
        android:id="@+id/passDataSourceButton"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Pass Data To Next Activity"/>

    <Button
        android:id="@+id/passDataReturnResultSourceButton"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Pass Data To Next Activity And Get Result Back"/>

    <TextView
        android:id="@+id/resultDataTextView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:textSize="20dp"/>

</LinearLayout>

4.2 Source Activity Java Code.

PassingDataSourceActivity.java

package com.dev2qa.example;

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

public class PassingDataSourceActivity extends AppCompatActivity {

    private final static int REQUEST_CODE_1 = 1;

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

        setTitle("dev2qa.com - Source Activity");

        // Click this button to pass data to target activity.
        Button passDataSourceButton = (Button)findViewById(R.id.passDataSourceButton);
        passDataSourceButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(PassingDataSourceActivity.this, PassingDataTargetActivity.class);
                intent.putExtra("message", "This message comes from PassingDataSourceActivity's first button");
                startActivity(intent);
            }
        });

        // Click this button to pass data to target activity and
        // then wait for target activity to return result data back.
        Button passDataReturnResultSourceButton = (Button)findViewById(R.id.passDataReturnResultSourceButton);
        passDataReturnResultSourceButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(PassingDataSourceActivity.this, PassingDataTargetActivity.class);
                intent.putExtra("message", "This message comes from PassingDataSourceActivity's second button");
                startActivityForResult(intent, REQUEST_CODE_1);
            }
        });
    }

    // This method is invoked when target activity return result data back.
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent dataIntent) {
        super.onActivityResult(requestCode, resultCode, dataIntent);

        // The returned result data is identified by requestCode.
        // The request code is specified in startActivityForResult(intent, REQUEST_CODE_1); method.
        switch (requestCode)
        {
            // This request code is set by startActivityForResult(intent, REQUEST_CODE_1) method.
            case REQUEST_CODE_1:
                TextView textView = (TextView)findViewById(R.id.resultDataTextView);
                if(resultCode == RESULT_OK)
                {
                    String messageReturn = dataIntent.getStringExtra("message_return");
                    textView.setText(messageReturn);
                }
        }
    }
}

4.3 Target Activity Layout Xml File.

activity_passing_data_target.xml

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical">

    <Button
        android:id="@+id/passDataTargetReturnDataButton"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Pass Result Data Back To Source Activity"/>

    <TextView
        android:id="@+id/requestDataTextView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:textSize="20dp"/>

</LinearLayout>

4.4 Target Activity Java Code.

User can go back to source activity by two methods.

  1. Click the return button in target activity. There are java code which listen to return Button click event.
  2. Type back menu in android device. You should override Activity.onBackPressed() method to process this event.
READ :   How To Register BroadcastReceiver In Android Activity

PassingDataTargetActivity.java

package com.dev2qa.example;

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

public class PassingDataTargetActivity extends AppCompatActivity {

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

        setTitle("dev2qa.com - Target Activity");

        // Get the transferred data from source activity.
        Intent intent = getIntent();
        String message = intent.getStringExtra("message");
        TextView textView = (TextView)findViewById(R.id.requestDataTextView);
        textView.setText(message);

        // Click this button to send response result data to source activity.
        Button passDataTargetReturnDataButton = (Button)findViewById(R.id.passDataTargetReturnDataButton);
        passDataTargetReturnDataButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent();
                intent.putExtra("message_return", "This data is returned when user click button in target activity.");
                setResult(RESULT_OK, intent);
                finish();
            }
        });
    }

    // This method will be invoked when user click android device Back menu at bottom.
    @Override
    public void onBackPressed() {
        Intent intent = new Intent();
        intent.putExtra("message_return", "This data is returned when user click back menu in target activity.");
        setResult(RESULT_OK, intent);
        finish();
    }
}
(Visited 10,865 times, 11 visits today)

3 Comments


  1. I’m new to android. But where is MainActivity?

    Reply

    1. Forget my question.
      I got it working.
      It took all of 10 minutes.
      I spent the last 6 hours trying to learn how to do this.
      I am sure I can step through the code and learn all I need.

      Thanks!

      Reply

      1. Don’t worry Buddy, You are not alone..

        Reply

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.