Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Android

Cách truyền dữ liệu giữa các Activity bằng Bundle trong Android

Hướng dẫn này minh họa cách truyền đối tượng dữ liệu phức tạp (custom object) giữa hai Activity bằng Bundle và Serializable.

Bước 1: Tạo dự án mới

Mở Android Studio, chọn File → New Project.

Bước 2: Model dữ liệu (src/UserInfo.java)

package com.example.sample;

import java.io.Serializable;

public class UserInfo implements Serializable {
    private String name;
    private String phone;

    public String getName() { return name; }
    public void setName(String name) { this.name = name; }
    public String getPhone() { return phone; }
    public void setPhone(String phone) { this.phone = phone; }
}

Bước 3: Giao diện màn hình 1 (res/layout/activity_main.xml)

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
    xmlns:android="https://schemas.android.com/apk/res/android"
    xmlns:app="https://schemas.android.com/apk/res-auto"
    xmlns:tools="https://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="center_horizontal"
        android:orientation="vertical"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintBottom_toBottomOf="parent"
        android:padding="16dp">

        <EditText
            android:id="@+id/etName"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:hint="Nhập tên"
            android:inputType="text" />

        <EditText
            android:id="@+id/etPhone"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="12dp"
            android:hint="Nhập số điện thoại"
            android:inputType="phone"/>

        <Button
            android:id="@+id/btnSend"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginTop="16dp"
            android:text="Gửi dữ liệu"/>

    </LinearLayout>
</androidx.constraintlayout.widget.ConstraintLayout>

Bước 4: Giao diện màn hình 2 (res/layout/activity_second.xml)

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="center"
    android:padding="16dp">

    <TextView
        android:id="@+id/tvData"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:textSize="20sp" />

</LinearLayout>

Bước 5: MainActivity - Gửi dữ liệu (src/MainActivity.java)

package com.example.sample;

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

public class MainActivity extends AppCompatActivity {
    EditText etName, etPhone;

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

        etName = findViewById(R.id.etName);
        etPhone = findViewById(R.id.etPhone);
        Button btnSend = findViewById(R.id.btnSend);

        btnSend.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String name = etName.getText().toString().trim();
                String phone = etPhone.getText().toString().trim();

                if (TextUtils.isEmpty(name) && TextUtils.isEmpty(phone)) {
                    Toast.makeText(MainActivity.this, "Vui lòng nhập thông tin", Toast.LENGTH_LONG).show();
                } else {
                    sendUserData(name, phone);
                }
            }
        });
    }

    private void sendUserData(String name, String phone) {
        UserInfo userInfo = new UserInfo();
        userInfo.setName(name);
        userInfo.setPhone(phone);

        Intent intent = new Intent(MainActivity.this, SecondActivity.class);
        Bundle bundle = new Bundle();
        bundle.putSerializable("user_data", userInfo);
        intent.putExtras(bundle);
        startActivity(intent);
    }
}

Bước 6: SecondActivity - Nhận dữ liệu (src/SecondActivity.java)

package com.example.sample;

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

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

        TextView tvData = findViewById(R.id.tvData);
        UserInfo userInfo = (UserInfo) getIntent().getSerializableExtra("user_data");

        if (userInfo != null) {
            String msg = "Tên: " + userInfo.getName() + "\nSĐT: " + userInfo.getPhone();
            tvData.setText(msg);
        }
    }
}

Bước 7: Manifest (AndroidManifest.xml)

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="https://schemas.android.com/apk/res/android" package="com.example.sample">
    <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" />
    </application>
</manifest>

💡 Các cách truyền dữ liệu khác

Phương phápPhù hợp choLưu ý
Intent.putExtra(key, value)Kiểu dữ liệu cơ bản (String, int, boolean...)Đơn giản, nhanh
Bundle + putSerializableObject phức tạp implement SerializableDễ dùng, nhưng chậm (reflection)
Bundle + putParcelableObject implement ParcelableHiệu năng tốt hơn Serializable
ViewModel + LiveDataChia sẻ dữ liệu giữa Fragment/Activity trong cùng tiến trìnhHiện đại, vòng đời tự động
Room Database / SharedPreferencesLưu trữ bền vững, chia sẻ toàn appDữ liệu lớn hoặc cần persist

Chạy ứng dụng

Kết nối thiết bị, nhấn Run. Nhập tên/SĐT, nhấn "Gửi dữ liệu" để xem kết quả trên màn hình 2.