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

Truyền dữ liệu giữa Activity Android dùng Intent.putExtra()

Cách trực tiếp và phổ biến nhất là sử dụng các phương thức putExtra() của Intent để đưa dữ liệu đơn lẻ. Dưới lớp, Intent tự tạo Bundle để chứa các extra này.

Ví dụ truyền String đơn giản

Bước 1: Tạo project

Android Studio → New Project → Empty Activity.

Bước 2: Layout MainActivity (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/edit_text"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:hint="Nhập tin nhắn"
        android:inputType="text" />

    <Button
        android:id="@+id/button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:layout_marginTop="16dp"
        android:text="Gửi Intent" />
</LinearLayout>

Bước 3: MainActivity.java - Gửi dữ liệu

package com.example.myapplication;

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

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

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

        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String message = editText.getText().toString().trim();

                Intent intent = new Intent(MainActivity.this, SecondActivity.class);
                // Truyền trực tiếp qua putExtra (key, value)
                intent.putExtra("EXTRA_MESSAGE", message);
                
                // Các overload khác:
                // intent.putExtra("EXTRA_NUMBER", 42);
                // intent.putExtra("EXTRA_FLAG", true);
                
                startActivity(intent);
            }
        });
    }
}

Bước 4: Layout SecondActivity (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/text_view"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:textSize="18sp" />
</LinearLayout>

Bước 5: SecondActivity.java - Nhận dữ liệu

package com.example.myapplication;

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

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

        TextView textView = findViewById(R.id.text_view);

        // Lấy dữ liệu từ Intent
        Intent intent = getIntent();
        if (intent != null && intent.hasExtra("EXTRA_MESSAGE")) {
            String message = intent.getStringExtra("EXTRA_MESSAGE");
            textView.setText("Tin nhắn: " + message);
        } else {
            textView.setText("Chưa nhận dữ liệu");
        }
    }
}

Bước 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" />
    </application>
</manifest>

Intent.putExtra() vs Bundle

Đặc điểm Intent.putExtra() Bundle + putExtras()
Cú pháp Ngắn gọn, trực tiếp Tạo Bundle trung gian
Đọc code Dễ hiểu cho 1-2 giá trị Rõ ràng khi nhiều giá trị
Hiệu năng Tương đương (Intent tạo Bundle ngầm) Tương đương
Truyền object phức tạp putExtra(key, parcelable/serializable) bundle.putParcelable/Serializable

Các phương thức getExtra phổ biến

  • getStringExtra(key) - Trả về null nếu key không tồn tại
  • getIntExtra(key, defaultValue) - Cần default value
  • getBooleanExtra(key, defaultValue)
  • getParcelableExtra(key) / getSerializableExtra(key)
  • getBundleExtra(key) - Lấy Bundle con
💡 Mẹo: Định nghĩa key dưới dạng public static final String trong class Activity hoặc một class Constants riêng để tránh lỗi chính tả key khi put/get.
public class MainActivity extends AppCompatActivity {
    public static final String EXTRA_MESSAGE = "com.example.myapp.MESSAGE";
    // ...
    intent.putExtra(EXTRA_MESSAGE, message);
}

Chạy ứng dụng

Build và Run ▶️. Nhập văn bản, nhấn "Gửi Intent", SecondActivity hiển thị nội dung nhận được.