Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Android

วิธีส่งข้อมูลกลับไปยัง Activity ก่อนหน้าใน Android

ภาพรวม

เมื่อต้องการส่งข้อมูลจาก Activity ปัจจุบันกลับไปยัง Activity ที่เปิดมัน (Previous Activity) ให้ใช้ startActivityForResult() และ onActivityResult() (API รุ่นเก่า) หรือ Activity Result APIs (แนะนำสำหรับ Android ใหม่)

หมายเหตุ: startActivityForResult() ถูก deprecated ใน Android X แนะนำให้ใช้ registerForActivityResult() แทน แต่ตัวอย่างนี้แสดงวิธีเดิมเพื่อความเข้าใจพื้นฐาน

ตัวอย่าง: ส่งข้อความจาก SecondActivity กลับ MainActivity

ขั้นตอนที่ 1: สร้างโปรเจกต์ใหม่

Android Studio → New Project → Empty Activity (Package: com.example.myapplication)

ขั้นตอนที่ 3: Layout หลัก (res/layout/activity_main.xml)

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
    xmlns:tools="https://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_margin="16dp"
    tools:context=".MainActivity">

    <TextView
        android:id="@+id/text_view"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:gravity="center"
        android:text="รอรับข้อมูล..."
        android:textSize="18sp" />

    <Button
        android:id="@+id/button"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_marginTop="16dp"
        android:text="Get Data" />
</RelativeLayout>

ขั้นตอนที่ 3: MainActivity.java - เรียก Activity และรับผลลัพธ์

package com.example.myapplication;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {
    private static final int MY_REQUEST_CODE = 1;
    private TextView textView;

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

        textView = findViewById(R.id.text_view);
        Button button = findViewById(R.id.button);

        button.setOnClickListener(v -> {
            Intent intent = new Intent(MainActivity.this, SecondActivity.class);
            startActivityForResult(intent, MY_REQUEST_CODE);
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == Activity.RESULT_OK) {
            if (requestCode == MY_REQUEST_CODE) {
                if (data != null) {
                    String value = data.getStringExtra("value");
                    textView.setText("ได้รับ: " + value);
                }
            }
        }
    }
}

ขั้นตอนที่ 4: Layout Activity ที่สอง (res/layout/activity_second.xml)

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
    xmlns:tools="https://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_margin="16dp"
    tools:context=".SecondActivity">

    <EditText
        android:id="@+id/edit_text"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:hint="Enter something to return previous activity"
        android:inputType="text" />

    <Button
        android:id="@+id/button"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_marginTop="16dp"
        android:text="Done" />
</RelativeLayout>

ขั้นตอนที่ 5: SecondActivity.java - ส่งข้อมูลกลับ

package com.example.myapplication;

import android.content.Intent;
import android.os.Bundle;
import androidx.appcompat.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

public class SecondActivity extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_second);

        EditText editText = findViewById(R.id.edit_text);
        Button button = findViewById(R.id.button);

        button.setOnClickListener(v -> {
            String value = editText.getText().toString().trim();
            Intent intent = new Intent();
            intent.putExtra("value", value);
            setResult(RESULT_OK, intent);
            finish(); // ปิด Activity นี้ กลับไป MainActivity
        });
    }
}

ขั้นตอนที่ 6: AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="https://schemas.android.com/apk/res/android"
    package="com.example.myapplication">
    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity android:name=".SecondActivity"></activity>
    </application>
</manifest>

วิธีการทำงาน (Legacy API)

  1. MainActivity เรียก startActivityForResult(intent, requestCode)
  2. SecondActivity ทำงาน เสร็จแล้ว เรียก setResult(RESULT_OK, intent) แล้ว finish()
  3. MainActivity ได้รับผลลัพธ์ใน onActivityResult(requestCode, resultCode, data)

วิธีใหม่: Activity Result API (แนะนำ)

สำหรับ Android ใหม่ (AndroidX Activity 1.2.0+) ให้ใช้วิธีนี้แทน:

// ใน MainActivity
private ActivityResultLauncher<Intent> launcher = registerForActivityResult(
    new ActivityResultContracts.StartActivityForResult(),
    result -> {
        if (result.getResultCode() == Activity.RESULT_OK && result.getData() != null) {
            String value = result.getData().getStringExtra("value");
            textView.setText("ได้รับ: " + value);
        }
    }
);

// เรียกใช้:
launcher.launch(new Intent(MainActivity.this, SecondActivity.class));

ข้อดีของ API ใหม่

  • Type-safe และไม่ต้องจัดการ requestCode เอง
  • แยก Logic การรับผลลัพธ์ชัดเจน
  • รองรับหลาย Activity Result พร้อมกันได้ง่าย
  • ทำงานร่วมกับ Fragment ได้ดี