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

Cách truyền đối tượng (Object) giữa các Activity trong Android

Giới thiệu

Hướng dẫn này trình bày cách truyền một đối tượng tùy chỉnh (custom object) từ Activity này sang Activity khác trong Android sử dụng Serializable và Intent.putExtra().

Các bước thực hiện

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

Mở Android Studio, chọn File → New Project và điền thông tin cần thiết.

Bước 2: Thiết kế giao diện Activity 1 (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"
    tools:context=".MainActivity">
    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Chuyển đối tượng sang Activity 2!"
        android:id="@+id/button"
        android:layout_centerInParent="true" />
</RelativeLayout>

Bước 3: Tạo class đối tượng (Character.java) - Implement Serializable

import java.io.Serializable;

public class Character implements Serializable {
    // Quan trọng: serialVersionUID để tránh lỗi khi class thay đổi
    private static final long serialVersionUID = 1L;
    
    String name;
    String profession;
    String position;
    String[] abilities;
    
    public Character(String name, String profession, String position, String[] abilities) {
        this.name = name;
        this.profession = profession;
        this.position = position;
        this.abilities = abilities;
    }
}

Bước 4: Logic Activity 1 (MainActivity.java)

import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;

public class MainActivity extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        
        Button button = findViewById(R.id.button);
        button.setOnClickListener(v -> {
            // Tạo đối tượng
            Character character = new Character(
                "CR7", 
                "Football", 
                "Left Winger", 
                new String[]{"Best Free kicker in the World", "Speed", "Heading"}
            );
            
            // Tạo Intent và putExtra
            Intent intent = new Intent(getApplicationContext(), SecondActivity.class);
            intent.putExtra("Character", character);
            startActivity(intent);
        });
    }
}

Bước 5: Tạo Activity 2 (SecondActivity.java)

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.TextView;
import java.util.Arrays;

public class SecondActivity extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_second);
        
        // Nhận đối tượng từ Intent
        Character character = (Character) getIntent().getSerializableExtra("Character");
        
        TextView textView = findViewById(R.id.textView);
        textView.setText(
            "Tên: " + character.name + "\n" +
            "Nghề: " + character.profession + "\n" +
            "Vị trí: " + character.position + "\n" +
            "Kỹ năng: " + Arrays.toString(character.abilities)
        );
    }
}

Bước 6: Giao diện Activity 2 (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"
    tools:context=".SecondActivity">
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/textView"
        android:textSize="20sp"
        android:layout_centerInParent="true" />
</RelativeLayout>

Bước 7: Khai báo Activity 2 trong Manifest

<activity android:name=".SecondActivity" />

So sánh các cách truyền dữ liệu

Phương pháp Ưu điểm Nhược điểm
Serializable Đơn giản, built-in Java Chậm, tạo nhiều object rác, reflection
Parcelable Nhanh, tối ưu cho Android Viết boilerplate code nhiều (dùng @Parcelize Kotlin)
Gson/JSON Linh hoạt, debug dễ Overhead serialize/deserialize
ViewModel/SharedViewModel Cycle-aware, survive rotation Chỉ trong cùng process

Parcelable (Khuyến nghị cho Android)

@Parcelize
data class Character(
    val name: String,
    val profession: String,
    val position: String,
    val abilities: Array<String>
) : Parcelable

Chạy ứng dụng

Kết nối thiết bị Android, nhấn Run trong Android Studio. Nhấn nút chuyển đối tượng, Activity 2 sẽ hiển thị thông tin cầu thủ.

Cách truyền đối tượng (Object) giữa các Activity trong Android

Cách truyền đối tượng (Object) giữa các Activity trong Android