Mission 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
-
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.
-
Create two activities:
Create two activities in the project, one for sending data and the other for receiving and processing data.
Right-click theapp
folder and selectNew
>Activity
to create these activities . -
Create two activities: Create two activities in the project, one for sending data and the other for receiving data. Name them
SendDataActivity
andReceiveDataActivity
respectively.
-
Design the SendDataActivity interface: Design the SendDataActivity interface in
activity_send_data.xml
, add an EditText and a Button for entering 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 effect
- Design the 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="这里将显示接收到的值"
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="返回数据"
android:layout_below="@id/receivedDataTextView"
android:layout_centerHorizontal="true"
android:layout_marginTop="16dp" />
</RelativeLayout>
achieve effect
- Send data in SendDataActivity: In
SendDataActivity.java
, usestartActivityForResult()
to send data to ReceiveDataActivity. First, define a request code (can be any integer) and a data keyTo 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);
}
});
}
}
- Receive data in ReceiveDataActivity: In
ReceiveDataActivity.java
, usegetIntent()
to receive data from SendDataActivity, and Display it in TextView.
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);
}
}
}
}
-
Processing return data: In
SendDataActivity
, use theonActivityResult()
method to process the data returned from < a i=4>The data returned.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 && data != null) { String receivedData = data.getStringExtra("dataFromReceive"); // 处理回传的数据 System.out.println(receivedData); } } }
-
Return data in ReceiveDataActivity: In
ReceiveDataActivity
, if you need to return data toSendDataActivity
, you can Postback viasetResult()
method.@Override public void onBackPressed() { // 在返回键按下时回传数据给SendDataActivity 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) {
// 在按钮点击事件中触发数据回传
String dataToReturn = "Data from ReceiveDataActivity";
Intent resultIntent = new Intent();
resultIntent.putExtra("dataFromReceive", dataToReturn);
setResult(RESULT_OK, resultIntent);
finish();
}
});
}
- Configure 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 effect
Below I will explain the principle and verify whether the data is successfully returned.
-
principle:
- When you start from
SendDataActivity
, you use the method, passing a request code ().ReceiveDataActivity
startActivityForResult()
REQUEST_CODE
- In
ReceiveDataActivity
, when the user presses the return key or clicks thereturnButton
button, you set the returned data and call a>setResult()
method to set the result code and pass data. - Then,
ReceiveDataActivity
callsfinish()
to close itself, passing the data back to theSendDataActivity
that called it. SendDataActivity
In , you implement theonActivityResult()
method. In this method, you check the returned request code and result code. If they meet expectations, start fromdata
Extract the returned data.
- When you start from
-
Verify whether the data is successfully returned:
- In
ReceiveDataActivity
, you set the return data in both the button click event and theonBackPressed()
method. This ensures that data will be returned regardless of whether the user clicks the button or the return key. - In
SendDataActivity
, you implement theonActivityResult()
method to receive the returned data.
- In
To verify that the data was successfully passed back, you can follow these steps:
- Run your application and open
SendDataActivity
. - Enter some data in
SendDataActivity
and click the Send button. - This will start
ReceiveDataActivity
and pass data to it. - In
ReceiveDataActivity
, you can see the passed data displayed inreceivedDataTextView
. - Then, you can click the back button or press the return key, and
ReceiveDataActivity
will be closed and the data will be passed back toSendDataActivity
. - In the method of
SendDataActivity
, you will see the returned data. You have used in this method to print the data, so you can see the printed data in the console.onActivityResult()
System.out.println()
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 () in
SendDataActivity
, and check whether the returned result code and data are in line with your expectations. To ensure the success of data return.REQUEST_CODE
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 the 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 the 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"
/>
<!-- 添加一个按钮来选择图片 -->
<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"
/>
<!-- 用于显示选择的图片 -->
<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 added aImageView
to display the selected image, and added 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"
/>
<!-- 添加一个ImageView来显示选择的图片 -->
<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 the 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); // 添加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);
}
});
// 添加按钮点击事件来选择图片
Button chooseImageButton = findViewById(R.id.chooseImageButton);
chooseImageButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// 打开系统图库应用
openGallery();
}
});
}
// 打开系统图库应用
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");
// 处理回传的文本数据
// ...
// 处理回传的图片数据
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 initialized and the button in the onCreate
method. Then, in the button's click event, we launch the gallery select image intent. ImageView
In theonActivityResult
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
and 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); // 添加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) {
// 在按钮点击事件中触发数据回传
String dataToReturn = "Data from ReceiveDataActivity";
Intent resultIntent = new Intent();
resultIntent.putExtra("dataFromReceive", dataToReturn);
setResult(RESULT_OK, resultIntent);
finish();
}
});
}
@Override
public void onBackPressed() {
// 在返回键按下时回传数据给SendDataActivity
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 inReceiveDataActivity
. Follow these steps to verify:
- Run the program and open
SendDataActivity
. - Click the “Select Image” button in
SendDataActivity
. - Select a picture (from the gallery).
- The selected image should be displayed in
ReceiveDataActivity
'sImageView
.
achieve effect