Passing Data Between Activities Android Tutorial

When you develop an android application, you always need to pass data between activities. And even more, you sometimes need to pass data between all activities for example pass session-id, user-name, and password. In this article, I will tell you how to use android Intent or Application object to pass data between activities.

1. Pass Data Between Activities Overview.

  1. There are two activities in this example, a Source Activity, and a Target Activity.
  2. The Source Activity contains two buttons ( PASS DATA TO NEXT ACTIVITY and PASS DATA TO NEXT ACTIVITY AND GET RESULT BACK ).
  3. The Target Activity contains one button ( PASS RESULT DATA BACK TO SOURCE ACTIVITY ).
  4. If you click the first button in the Source Activity, it will pass data to the Target Activity, and when you click the return button in the Target Activity, the Source Activity can not get the response data from Target Activity. See the video demo from https://youtu.be/SKjZblBXoik.
  5. If you click the second button in the Source Activity, it will pass data to the Target Activity also, and when you click the return button or click the android Back menu at the bottom in the Target Activity, the Source Activity can get the Target Activity returned response result data and display the result text in the Source Activity. See the video demon from https://youtu.be/4_cBFxwtc50.

2. Pass Data Between Activities Use Intent Object.

  1. Create an instance of android.content.Intent class, pass the Source Activity object ( who sent the intent object ) and the Target Activity class ( who can receive the intent object ) to the Intent class constructor.
    Intent intent = new Intent(PassingDataSourceActivity.this, PassingDataTargetActivity.class);
  2. Invoke the above intent object’s putExtra(String key, Object data) method to store the data that will pass to Target Activity in it.
    intent.putExtra("message", "This message comes from PassingDataSourceActivity's first button");
  3. Invoke Source Activity object’s startActivity(intent) method to pass the intent object to the android os.
    startActivity(intent);
  4. In the Target Activity,  call getIntent() method to get the Source Activity sent intent object.
    Intent intent = getIntent()
  5. In the Target Activity, call the above intent object’s getStringExtra(String key) to get Source Activity passed data. The key should be the same as step 2 when invoking the intent object’s putExtra method.
    String message = intent.getStringExtra("message");

3. Pass Data Back From Target Activity.

  1. Create a New Explicit or Implicit android.content.Intent class’s instance in the Source Activity.
    Intent intent = new Intent(PassingDataSourceActivity.this, PassingDataTargetActivity.class);
  2. Store the passed data in the above intent object by invoking its putExtra(String key, Object data) method, the key is a message key, the data is the passed data value.
    intent.putExtra("message", "This message comes from PassingDataSourceActivity's second button");
  3. If you want to get the response data from the Target Activity, now you should call startActivityForResult(Intent intent, int requestCode) method in the Source Activity, this method will pass the intent object to android os and wait for the response from the Target Activity. The first parameter is the intent object, the second parameter is a user-defined integer number that is used to check whether the returned intent object is related to this request.
    startActivityForResult(intent, REQUEST_CODE_1);
  4. To return data back to Source Activity from the Target Activity, you should create an instance of android.content.Intent class in the Target Activity. Do not need to provide constructor parameters at this time.
    Intent intent = new Intent();
  5. Call above intent object’s putExtra(String key, Object data) method to set the returned result data in the intent object.
    intent.putExtra("message_return", "This data is returned when user click button in target activity.");
  6. Call setResult(RESULT_OK, intent) method in the Target Activity to set the returned intent in android os. The first parameter can be android.app.Activity.RESULT_OK or RESULT_CANCELED, the second parameter is the intent object.
    setResult(RESULT_OK, intent);
  7. In the Source Activity java class, override onActivityResult(int requestCode, int resultCode, Intent dataIntent) method, the requestCode is just the user-defined integer number that is passed in above startActivityForResult method, use the requestCode to check which startActivityForResult request can use the returned dataIntent object if there are multiple places invoke the startActivityForResult method in the Source Activity. The resultCode value shows whether the request is ok or canceled.
    @Override 
    protected void onActivityResult(int requestCode, int resultCode, Intent dataIntent) 
    { 
        super.onActivityResult(requestCode, resultCode, dataIntent); 
    
        switch (requestCode) 
        { 
           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. Pass Data Between Activities 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.

Users can go back to source activity by two methods.

  1. Click the return button in the target activity. There is java code that listens to the return Button click event.
  2. Type back menu in android device. You should override Activity.onBackPressed() method to process this event.

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 passed 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();
    }
}

5. How To Share Data Between Multiple Activities.

  1. A reader comments that he has multiple activities, each activity want to set some data in somewhere, and when all the activities set data finished, the last activity will send all the activities saved data to a database, how to implement this?
  2. There are 2 methods to share data between activities.1. Share data in memory. 2. Share data in a local file. When your last activity wants to save the data to the database, it can either read the data from memory or a local file then save the data to the database.
  3. To share data in memory, you can use the android application singleton, you should create your own android java class that extends the android.app.Application class. Then your android application instance will be created when the android app startup. Below is the source code of your own android application class.
    // Import android.app.Application class.
    import android.app.Application;
    
    // Create your own android Application class.
    public class MyOwnApplication extends Application {
    
        // Used to share data across multiple activities in the same android application.
        private String data;
    
        // Define get data method.
        public String getData() {
            return data;
        }
    
        // Define set data method.
        public void setData(String data) {
            this.data = data;
        }
    }

    Now in each activity, you can run the code MyOwnApplication app = MyOwnApplication.getApplicationContext(); to get the application object, then call the app.setData(data) method to set the share data.

    In the last activity which you want to save the data to a database, you can run the code MyOwnApplication app = MyOwnApplication.getApplicationContext(); to get the application object, and then call the code app.getData() to get the data saved by multiple activities. Now you can save the shared data into a database.

  4. You can read the article Android Get Application Context From Anywhere Example to learn more about how to use android application context to share data.
  5. The other way is to save the shared data in a local file, you can read the article Android Shared Preferences Example, Android Sharedpreferences Save/Load Java Object Example to learn more.
0 0 vote
Article Rating
Subscribe
Notify of
guest

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

12 Comments
Newest
Oldest Most Voted
Inline Feedbacks
View all comments
matt
matt

Can you send data from different activities to one activity using intent.Say for instance you have different forms in different activities but you want an activity that sends it all to a database

Amol Chaure
Amol Chaure

Thank you very much!!!. It cleared many doubts.

Virti Parekh
Virti Parekh

i want to pass data which is retrieve from firebase , when i pressed button on the first activity it will retrieve the data from firebase and show it in the second activity is it possible ???can You please help!

Hinduja
Hinduja

How to create a database by sending the database name while switching between activities .

OrionRed
OrionRed

Please don’t give up! I am 52 and have been learning this for the last year in my spare time. One thing I can recommend is to make up a simple need an write a program to do it. Start with a “hello world” program and move up from there. You’ll learn slowly but steadily. It’s not like desktop at all. It’s as big a jump for me as it was to go from COBOL to C++.

Joe Reidy
Joe Reidy

I also had the same problem did you figure this out?

Pete Cal
Pete Cal

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

Pete Cal
Pete Cal
Reply to  Pete Cal

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!

MuthuKumar
MuthuKumar
Reply to  Pete Cal

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

Housam
Housam
Reply to  Pete Cal

Thanks for the response
could you please tell : how to pass data by The button”X” and start an activity with The button “y” ,,
passing value without starting activities
or make the value obtained”Z” a Global value that can be obtained and used from differentes activities ??

ajith
ajith
Reply to  Pete Cal

Main activity is just a name used in android studio during project creation. you can name you activity as you like. don’t get confused with the naming..

12
0
Would love your thoughts, please comment.x
()
x