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

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

  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.
    Insert image description here

  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.
    Insert image description here
    Insert image description here

  4. Design the SendDataActivity interface: Design the SendDataActivity interface inactivity_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
Insert image description here

  1. Design the ReceiveDataActivity interface: Design the ReceiveDataActivity interface inactivity_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
Insert image description here

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

}
  1. Receive data in ReceiveDataActivity: In ReceiveDataActivity.java, use getIntent() 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);
            }
        }
    }
}
  1. Processing return data: In SendDataActivity, use the onActivityResult() 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);
            }
        }
    }
    
  2. Return data in ReceiveDataActivity: In ReceiveDataActivity, if you need to return data to SendDataActivity, you can Postback via setResult() 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();
            }
        });
    }
  1. 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
Please add image description

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

  1. principle:

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

    • InReceiveDataActivity, 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.
    • InSendDataActivity, 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 openSendDataActivity.
  2. Enter some data inSendDataActivity and click the Send button.
  3. This will startReceiveDataActivity and pass data to it.
  4. InReceiveDataActivity, you can see the passed data displayed inreceivedDataTextView.
  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 method ofSendDataActivity, 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

Insert image description here
Insert image description here

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
Insert image description here

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:

  1. Run the program and openSendDataActivity.
  2. Click the “Select Image” button inSendDataActivity.
  3. Select a picture (from the gallery).
  4. The selected image should be displayed inReceiveDataActivity'sImageView.

achieve effect
Please add image description

Guess you like

Origin blog.csdn.net/qq_22841387/article/details/133584986