Data return between activities [Android, activity return, combined examples]

Task requirements

In Android applications, sometimes it is necessary to pass data from one Activity to another Activity and pass the results back to the first Activity after processing by the second Activity.

In this case, we can use the startActivityForResult() and onActivityResult() methods to implement data return.

Implementation steps

  1. Create a new Android project:
    Open Android Studio and create a new Android project, making sure to select the appropriate project name and package name.

  2. Create two activities:
    Create two activities in the project, one for sending data and the other for receiving and processing data.
    Right-click the app folder and select New > Activity to create these activities.

  3. Create two activities: Create two activities in the project, one for sending data and the other for receiving data. Name them SendDataActivity and ReceiveDataActivity respectively.

  4. Design SendDataActivity interface: Design the SendDataActivity interface in activity_send_data.xml, add an EditText and a Button for inputting data and sending it.

    <?xml version="1.0" encoding="utf-8"?>
    <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        xmlns:tools="http://schemas.android.com/tools"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        tools:context=".SendDataActivity">
    
        <EditText
            android:id="@ + id/editText"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:hint="Enter data to send"
            android:layout_centerVertical="true"
            android:layout_centerHorizontal="true" />
    
        <Button
            android:id="@ + id/sendButton"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Send Data"
            android:layout_below="@id/editText"
            android:layout_centerHorizontal="true"
            android:layout_marginTop="16dp" />
    
    </RelativeLayout>
    

Achieve results

  1. Design ReceiveDataActivity interface: Design the ReceiveDataActivity interface in activity_receive_data.xml and add a TextView to display the received data.
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".ReceiveDataActivity">

    <TextView
        android:id="@ + id/receivedDataTextView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:text="The received value will be displayed here"
        android:textSize="24sp"
        android:textColor="#FF5733"
        android:textStyle="bold"
        android:letterSpacing="0.05"
        android:lineSpacingExtra="8dp"
        android:background="#F2F2F2"
        android:padding="16dp"
        android:drawablePadding="8dp" />

    <Button
        android:id="@ + id/returnButton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="return data"
        android:layout_below="@id/receivedDataTextView"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="16dp" />

</RelativeLayout>

Achieve results

  1. Send data in SendDataActivity: In SendDataActivity.java, use startActivityForResult() to send data to ReceiveDataActivity. First, define a request code (can be any integer) and a data key to identify the data.
package com.leo.activitytransfer;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

public class SendDataActivity extends AppCompatActivity {<!-- -->

    private static final int REQUEST_CODE = 1;
    private EditText editText;

    @Override
    protected void onCreate(Bundle savedInstanceState) {<!-- -->
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_send_data);

        editText = findViewById(R.id.editText);
        Button sendButton = findViewById(R.id.sendButton);

        sendButton.setOnClickListener(new View.OnClickListener() {<!-- -->
            @Override
            public void onClick(View v) {<!-- -->
                String dataToSend = editText.getText().toString();
                Intent intent = new Intent(SendDataActivity.this, ReceiveDataActivity.class);
                intent.putExtra("data", dataToSend);
                startActivityForResult(intent, REQUEST_CODE);
            }
        });
    }

}
  1. Receive data in ReceiveDataActivity: In ReceiveDataActivity.java, use getIntent() to receive data from SendDataActivity and display it in TextView middle.
package com.leo.activitytransfer;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.os.Bundle;
import android.widget.TextView;

public class ReceiveDataActivity extends AppCompatActivity {<!-- -->

    private TextView receivedDataTextView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {<!-- -->
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_receive_data);

        receivedDataTextView = findViewById(R.id.receivedDataTextView);

        Intent intent = getIntent();
        if (intent != null) {<!-- -->
            String receivedData = intent.getStringExtra("data");
            if (receivedData != null) {<!-- -->
                receivedDataTextView.setText(receivedData);
            }
        }
    }
}
  1. Processing return data: In SendDataActivity, use the onActivityResult() method to process the data returned from ReceiveDataActivity .

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {<!-- -->
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_CODE) {<!-- -->
            if (resultCode == RESULT_OK & amp; & amp; data != null) {<!-- -->
                String receivedData = data.getStringExtra("dataFromReceive");
                // Process the returned data
                System.out.println(receivedData);
            }
        }
    }
    
  2. Return data in ReceiveDataActivity: In ReceiveDataActivity, if you need to return data to SendDataActivity, you can use setResult() code> method to return.

     @Override
     public void onBackPressed() {<!-- -->
         // Return data to SendDataActivity when the return key is pressed
         String dataToReturn = "Data from ReceiveDataActivity";
         Intent resultIntent = new Intent();
         resultIntent.putExtra("dataFromReceive", dataToReturn);
         setResult(RESULT_OK, resultIntent);
         finish();
     }
    

Of course, you can also directly set the response event of the return button

 private TextView receivedDataTextView;
    private Button returnButton;

    @Override
    protected void onCreate(Bundle savedInstanceState) {<!-- -->
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_receive_data);

        receivedDataTextView = findViewById(R.id.receivedDataTextView);
        returnButton = findViewById(R.id.returnButton);

        Intent intent = getIntent();
        if (intent != null) {<!-- -->
            String receivedData = intent.getStringExtra("data");
            if (receivedData != null) {<!-- -->
                receivedDataTextView.setText(receivedData);
            }
        }

        returnButton.setOnClickListener(new View.OnClickListener() {<!-- -->
            @Override
            public void onClick(View v) {<!-- -->
                // Trigger data postback in button click event
                String dataToReturn = "Data from ReceiveDataActivity";
                Intent resultIntent = new Intent();
                resultIntent.putExtra("dataFromReceive", dataToReturn);
                setResult(RESULT_OK, resultIntent);
                finish();
            }
        });
    }
  1. Configuring AndroidManifest.xml: Ensure that the declarations of the two Activity are correctly configured in the AndroidManifest.xml file.
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
 xmlns:tools="http://schemas.android.com/tools">

 <application
     android:allowBackup="true"
     android:dataExtractionRules="@xml/data_extraction_rules"
     android:fullBackupContent="@xml/backup_rules"
     android:icon="@mipmap/ic_launcher"
     android:label="@string/app_name"
     android:roundIcon="@mipmap/ic_launcher_round"
     android:supportsRtl="true"
     android:theme="@style/Theme.AppCompat.DayNight"
     tools:targetApi="31">
     <activity
         android:name=".SendDataActivity"
         android:exported="true"
         android:label="@string/app_name"
         android:theme="@style/Theme.AppCompat.DayNight">
         <intent-filter>
             <action android:name="android.intent.action.MAIN" />

             <category android:name="android.intent.category.LAUNCHER" />
         </intent-filter>
     </activity>
     <activity
         android:name=".ReceiveDataActivity"
         android:exported="false" />
 </application>

</manifest>

Achieve results
Please add image description

Below I will explain the principle and verify whether the data is successfully returned.

  1. principle:

    • When you start ReceiveDataActivity from SendDataActivity, you use the startActivityForResult() method, passing a request code (REQUEST_CODE ).
    • In ReceiveDataActivity, when the user presses the return key or clicks the returnButton button, you set the returned data and call setResult()Methods to set result codes and pass data.
    • Then, ReceiveDataActivity calls finish() to close itself and pass the data back to the SendDataActivity that called it.
    • In SendDataActivity, you implement the onActivityResult() method. In this method, you check the returned request code and result code. If they meet expectations, start from Extract the returned data from data.
  2. Verify whether the data is successfully returned:

    • In ReceiveDataActivity, you set the return data in both the button click event and the onBackPressed() method. This ensures that data will be returned regardless of whether the user clicks the button or the return key.
    • In SendDataActivity, you implement the onActivityResult() method to receive the returned data.

To verify that the data was successfully passed back, you can follow these steps:

  1. Run your application and open SendDataActivity.
  2. Enter some data in SendDataActivity and click the send button.
  3. This will start ReceiveDataActivity and pass the data to it.
  4. In ReceiveDataActivity, you can see the passed data displayed in receivedDataTextView.
  5. Then, you can click the back button or press the return key, and ReceiveDataActivity will be closed and the data will be passed back to SendDataActivity.
  6. In the onActivityResult() method of SendDataActivity, you will see the returned data. You have used System.out.println() in this method to print the data, so you can see the printed data in the console.

If you see that the data output in the console is “Returned Data Data from ReceiveDataActivity”, it means that the data was successfully returned. This is how you verify that the data was successfully passed back.

Please make sure to use the correct request code (REQUEST_CODE) in SendDataActivity, and check whether the result code and data returned are in line with your expectations to ensure the success of the data return or not.

Application example: Implement image selection and display:

If we want to implement image selection and display functions, we can use Android’s image selector to achieve it. In the Activity that receives the data, start the image picker and then after successfully selecting the image, pass the URI of the image to the Activity that sends the data.

1. Add permissions in AndroidManifest.xml:

<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />

This is to gain access to external storage.

2. Create placeholder_image.xml file:

In order to display the default placeholder image in ImageView, we can take a photo directly in the virtual machine


3. Modify layout file:
activity_send_data.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:padding="16dp"
    tools:context=".SendDataActivity">

    <EditText
        android:id="@ + id/editText"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="Enter text..."
        android:layout_marginBottom="16dp"
        />

    <Button
        android:id="@ + id/sendButton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Send Data"
        android:layout_below="@id/editText"
        />

    <!-- Add a button to select an image -->
    <Button
        android:id="@ + id/chooseImageButton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Choose Image"
        android:layout_below="@id/sendButton"
        android:layout_marginTop="16dp"
        />

    <!-- Used to display the selected image -->
    <ImageView
        android:id="@ + id/selectedImageView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@id/chooseImageButton"
        android:layout_marginTop="16dp"
        android:visibility="gone"
    />
</RelativeLayout>

Here we add an ImageView to display the selected image, and add a button to trigger the image selection operation.
Achieve results

activity_receive_data.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:padding="16dp"
    tools:context=".ReceiveDataActivity">

    <TextView
        android:id="@ + id/receivedDataTextView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginBottom="16dp"
        android:text=""
        />

    <Button
        android:id="@ + id/returnButton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Return Data"
        android:layout_below="@id/receivedDataTextView"
        />

    <!-- Add an ImageView to display the selected image -->
    <ImageView
        android:id="@ + id/receivedImageView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@id/returnButton"
        android:layout_marginTop="16dp"
        android:visibility="gone"
    />
</RelativeLayout>

3. Modify activity file:
SendDataActivity.java

package com.leo.transfer;

import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

public class SendDataActivity extends AppCompatActivity {<!-- -->

    private static final int REQUEST_CODE = 1;
    private EditText editText;
    private ImageView selectedImageView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {<!-- -->
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_send_data);

        editText = findViewById(R.id.editText);
        Button sendButton = findViewById(R.id.sendButton);
        selectedImageView = findViewById(R.id.selectedImageView); // Add a reference to ImageView

        sendButton.setOnClickListener(new View.OnClickListener() {<!-- -->
            @Override
            public void onClick(View v) {<!-- -->
                String dataToSend = editText.getText().toString();
                Intent intent = new Intent(SendDataActivity.this, ReceiveDataActivity.class);
                intent.putExtra("data", dataToSend);
                startActivityForResult(intent, REQUEST_CODE);
            }
        });

        //Add button click event to select image
        Button chooseImageButton = findViewById(R.id.chooseImageButton);
        chooseImageButton.setOnClickListener(new View.OnClickListener() {<!-- -->
            @Override
            public void onClick(View v) {<!-- -->
                //Open the system gallery application
                openGallery();
            }
        });
    }

    //Open the system gallery application
    private void openGallery() {<!-- -->
        Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
        startActivityForResult(intent, REQUEST_CODE);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {<!-- -->
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_CODE) {<!-- -->
            if (resultCode == RESULT_OK) {<!-- -->
                if (data != null) {<!-- -->
                    String receivedData = data.getStringExtra("dataFromReceive");
                    // Process the returned text data
                    // ...

                    // Process the returned image data
                    Uri selectedImageUri = data.getData();
                    if (selectedImageUri != null) {<!-- -->
                        Intent intent = new Intent(SendDataActivity.this, ReceiveDataActivity.class);
                        intent.putExtra("dataFromSend", receivedData);
                        intent.putExtra("imageUri", selectedImageUri.toString());
                        startActivityForResult(intent, REQUEST_CODE);
                    }
                }
            }
        }
    }

}

In this code, we first initialize the ImageView and button in the onCreate method. Then, in the button’s click event, we launch the gallery select image intent.

In the onActivityResult method, we check whether the correct request code (REQUEST_CODE) and result code are returned. If everything goes well, we get the URI of the selected image and use the MediaStore.Images.Media.getBitmap() method to load the image into ImageView to display it.

ReceiveDataActivity.java

package com.leo.transfer;

import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.appcompat.app.AppCompatActivity;

public class ReceiveDataActivity extends AppCompatActivity {<!-- -->

    private TextView receivedDataTextView;
    private ImageView receivedImageView;
    private Button returnButton;

    @Override
    protected void onCreate(Bundle savedInstanceState) {<!-- -->
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_receive_data);

        receivedDataTextView = findViewById(R.id.receivedDataTextView);
        receivedImageView = findViewById(R.id.receivedImageView); // Add a reference to ImageView
        returnButton = findViewById(R.id.returnButton);

        Intent intent = getIntent();
        if (intent != null) {<!-- -->
            String receivedData = intent.getStringExtra("dataFromSend");
            if (receivedData != null) {<!-- -->
                receivedDataTextView.setText(receivedData);
            }

            String imageUriString = intent.getStringExtra("imageUri");
            if (imageUriString != null) {<!-- -->
                Uri imageUri = Uri.parse(imageUriString);
                try {<!-- -->
                    Bitmap bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), imageUri);
                    receivedImageView.setVisibility(View.VISIBLE);
                    receivedImageView.setImageBitmap(bitmap);
                } catch (Exception e) {<!-- -->
                    e.printStackTrace();
                }
            }
        }

        returnButton.setOnClickListener(new View.OnClickListener() {<!-- -->
            @Override
            public void onClick(View v) {<!-- -->
                // Trigger data postback in button click event
                String dataToReturn = "Data from ReceiveDataActivity";
                Intent resultIntent = new Intent();
                resultIntent.putExtra("dataFromReceive", dataToReturn);
                setResult(RESULT_OK, resultIntent);
                finish();
            }
        });
    }

    @Override
    public void onBackPressed() {<!-- -->
        // Return data to SendDataActivity when the return key is pressed
        String dataToReturn = "Data from ReceiveDataActivity";
        Intent resultIntent = new Intent();
        resultIntent.putExtra("dataFromReceive", dataToReturn);
        setResult(RESULT_OK, resultIntent);
        finish();
    }
}

Our application now allows the user to select an image and display it in ReceiveDataActivity. Follow these steps to verify:

  1. Run the program and open SendDataActivity.
  2. Click the “Select Image” button in SendDataActivity.
  3. Select a picture (from the gallery).
  4. The selected image should be displayed in the ImageView of ReceiveDataActivity.

Achieve results
Please add image description