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

วิธีส่งข้อมูลหลายรายการระหว่าง Activity ใน Android

ภาพรวม

วิธีพื้นฐานในการส่งข้อมูลหลายค่าระหว่าง Activity คือใช้ Bundle ผ่าน Intent.putExtras() เหมาะสำหรับข้อมูลขนาดเล็กถึงปานกลาง เช่น String, int, boolean

ตัวอย่าง: ส่ง Name และ Age จาก MainActivity ไป SecondActivity

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

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

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

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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"
    android:orientation="vertical"
    tools:context=".MainActivity">

    <EditText
        android:id="@+id/etName"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="Name"
        android:inputType="text" />

    <EditText
        android:id="@+id/etAge"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="Age"
        android:inputType="number" />

    <Button
        android:id="@+id/button"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="16dp"
        android:text="Next" />
</LinearLayout>

ขั้นตอนที่ 3: MainActivity.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 MainActivity extends AppCompatActivity {
    private EditText etName, etAge;

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

        etName = findViewById(R.id.etName);
        etAge = findViewById(R.id.etAge);
        Button button = findViewById(R.id.button);

        button.setOnClickListener(v -> {
            String name = etName.getText().toString().trim();
            String age = etAge.getText().toString().trim();

            // ใช้ Bundle เพื่อจัดกลุ่มข้อมูลหลายค่า
            Bundle bundle = new Bundle();
            bundle.putString("name", name);
            bundle.putString("age", age);
            // สามารถเพิ่มชนิดข้อมูลอื่นได้: putInt, putBoolean, putParcelable, etc.

            Intent intent = new Intent(MainActivity.this, SecondActivity.class);
            intent.putExtras(bundle);
            startActivity(intent);
        });
    }
}

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

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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"
    android:orientation="vertical"
    tools:context=".SecondActivity">

    <TextView
        android:id="@+id/tvName"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:textSize="18sp" />

    <TextView
        android:id="@+id/tvAge"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:textSize="18sp" />
</LinearLayout>

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

package com.example.myapplication;

import android.os.Bundle;
import androidx.appcompat.app.AppCompatActivity;
import android.widget.TextView;

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

        TextView tvName = findViewById(R.id.tvName);
        TextView tvAge = findViewById(R.id.tvAge);

        Bundle bundle = getIntent().getExtras();
        if (bundle != null) {
            String name = bundle.getString("name", ""); // ค่า default ป้องกัน null
            String age = bundle.getString("age", "");
            tvName.setText("Name: " + name);
            tvAge.setText("Age: " + age);
        }
    }
}

ขั้นตอนที่ 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>

วิธีการทำงาน

  1. ผู้ใช้กรอก Name และ Age ใน MainActivity
  2. กด Next → ข้อมูลถูกใส่ใน Bundle ด้วย key "name" และ "age"
  3. Bundle ถูกส่งผ่าน Intent ไป SecondActivity
  4. SecondActivity ดึงค่ากลับด้วย getString() โดยใช้ key เดียวกัน

รูปแบบข้อมูลที่รองรับใน Bundle

เมธอดชนิดข้อมูล
putString / getStringString
putInt / getIntint
putBoolean / getBooleanboolean
putDouble / getDoubledouble
putParcelable / getParcelableParcelable object
putSerializable / getSerializableSerializable object
putStringArray / getStringArrayString[]

แนวทางปฏิบัติที่ดี

  • ใช้ key แบบคงที่ (constant) เพื่อป้องกัน typo: public static final String KEY_NAME = "key_name";
  • ตรวจสอบ null ก่อนใช้งาน: bundle.getString("key", "default")
  • สำหรับข้อมูลซับซ้อน ใช้ Parcelable (เร็วกว่า Serializable)
  • หลีกเลี่ยงการส่งข้อมูลขนาดใหญ่ผ่าน Intent (จำกัด ~1MB)