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

Các cách truyền dữ liệu giữa hai Activity trong Android không dùng Intent

Trong phát triển Android, cách phổ biến nhất để truyền dữ liệu giữa các Activity là sử dụng Intent kèm Bundle. Tuy nhiên, vẫn tồn tại các phương pháp替代 cho các trường hợp đặc biệt. Bài viết này giới thiệu hai cách tiếp cận: sử dụng biến static và SharedPreferences.

Phương pháp 1: Sử dụng biến static (Chỉ dùng cho dữ liệu đơn giản, vòng đời ngắn)

Cách này lưu trữ dữ liệu trong một biến tĩnh của Activity nguồn. Dữ liệu sẽ mất khi tiến trình ứng dụng bị hệ thống hủy.

Bước 1: Tạo project mới

Mở Android Studio → File → New Project → Chọn Empty Activity → Điền thông tin cần thiết.

Bước 2: Thiết kế giao diện 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 nội dung cần truyề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="Next" />
</LinearLayout>

Bước 3: Code MainActivity.java

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 {
    private static String sharedValue;

    public static String getSharedValue() {
        return sharedValue;
    }

    @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) {
                sharedValue = editText.getText().toString().trim();
                Intent intent = new Intent(MainActivity.this, SecondActivity.class);
                startActivity(intent);
            }
        });
    }
}

Bước 4: Thiết kế 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" />
</LinearLayout>

Bước 5: Code SecondActivity.java

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);
        textView.setText(MainActivity.getSharedValue());
    }
}

Bước 6: Cấu hình 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>

Phương pháp 2: Sử dụng SharedPreferences (Dữ liệu bền vững, phù hợp cài đặt/token)

Dữ liệu được ghi vào file XML riêng tư của ứng dụng, tồn tại sau khi đóng app.

Bước 3 (cập nhật): MainActivity.java với SharedPreferences

package com.example.myapplication;

import android.content.Intent;
import android.content.SharedPreferences;
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 {
    private static final String PREF_NAME = "MyAppPrefs";
    private static final String KEY_VALUE = "passed_value";

    @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 value = editText.getText().toString().trim();
                
                SharedPreferences sharedPref = getSharedPreferences(PREF_NAME, MODE_PRIVATE);
                SharedPreferences.Editor editor = sharedPref.edit();
                editor.putString(KEY_VALUE, value);
                editor.apply();

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

Bước 5 (cập nhật): SecondActivity.java đọc SharedPreferences

package com.example.myapplication;

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

public class SecondActivity extends AppCompatActivity {
    private static final String PREF_NAME = "MyAppPrefs";
    private static final String KEY_VALUE = "passed_value";

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

        TextView textView = findViewById(R.id.text_view);
        SharedPreferences sharedPreferences = getSharedPreferences(PREF_NAME, MODE_PRIVATE);
        String value = sharedPreferences.getString(KEY_VALUE, "");
        textView.setText(value);
    }
}

So sánh và lưu ý quan trọng

Tiêu chí Biến static SharedPreferences
Độ bền dữ liệu Mất khi process chết Lưu trữ vĩnh viễn
Phạm vi truy cập Toàn ứng dụng (public static) Riêng tư ứng dụng (private mode)
Hiệu năng Rất nhanh (RAM) Chậm hơn (I/O file)
Phù hợp cho Dữ liệu tạm, object phức tạp Cài đặt, token, dữ liệu nhỏ
⚠️ Cảnh báo: Việc dùng biến static để truyền dữ liệu giữa Activity không được khuyến khích trong sản phẩm thực tế vì:
  • Gây rò rỉ bộ nhớ (memory leak) nếu giữ reference Context/View.
  • Dữ liệu mất khi Android kill process để giải phóng tài nguyên.
  • Vi phạm nguyên tắc đóng gói, khó test và bảo trì.
Best practice: Luôn ưu tiên Intent + Bundle/Parcelable hoặc ViewModel (Jetpack) cho kiến trúc hiện đại.

Chạy ứng dụng

Kết nối thiết bị thật hoặc chạy emulator. Nhấn Run ▶️ từ toolbar, chọn thiết bị. Nhập văn bản, bấm "Next" để xem kết quả trên SecondActivity.