Khi cần truyền đối tượng phức tạp hoặc danh sách dữ liệu lớn giữa các Activity, cách hiệu quả nhất là implement interface Serializable cho lớp model và gửi qua Bundle kèm theo Intent.
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, tạo dự án với package com.example.myapplication.
Bước 2: Thiết kế màn hình chính (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:layout_gravity="center"
android:hint="Tên"
android:inputType="textCapWords" />
<EditText
android:id="@+id/etAge"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:hint="Tuổi"
android:inputType="number" />
<EditText
android:id="@+id/etCity"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:hint="Thành phố"
android:inputType="textCapWords" />
<Button
android:id="@+id/button"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_marginTop="16dp"
android:text="Tiếp theo" />
</LinearLayout>
Bước 3: Tạo lớp Model implements Serializable (src/User.java)
package com.example.myapplication;
import java.io.Serializable;
public class User implements Serializable {
private String city;
private String name;
private String age;
public User(String name, String age, String city) {
this.name = name;
this.age = age;
this.city = city;
}
// Getters và Setters
public String getCity() { return city; }
public void setCity(String city) { this.city = city; }
public String getName() { return name; }
public void setName(String name) { this.name = name; }
public String getAge() { return age; }
public void setAge(String age) { this.age = age; }
}
Bước 4: Xử lý gửi dữ liệu (src/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;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
private EditText etName, etAge, etCity;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
etName = findViewById(R.id.etName);
etAge = findViewById(R.id.etAge);
etCity = findViewById(R.id.etCity);
Button button = findViewById(R.id.button);
button.setOnClickListener(v -> {
String name = etName.getText().toString().trim();
String age = etAge.getText().toString().trim();
String city = etCity.getText().toString().trim();
// Tạo danh sách User (có thể chứa nhiều đối tượng)
ArrayList<User> userList = new ArrayList<>();
userList.add(new User(name, age, city));
// Đóng gói vào Bundle
Bundle bundle = new Bundle();
bundle.putSerializable("myUser", userList);
// Gửi qua Intent
Intent intent = new Intent(MainActivity.this, SecondActivity.class);
intent.putExtras(bundle);
startActivity(intent);
});
}
}
Bước 5: Thiết kế màn hình nhận (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/textView"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</LinearLayout>
Bước 6: Nhận và hiển thị dữ liệu (src/SecondActivity.java)
package com.example.myapplication;
import android.os.Bundle;
import androidx.appcompat.app.AppCompatActivity;
import android.widget.TextView;
import java.util.ArrayList;
public class SecondActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
Bundle bundle = getIntent().getExtras();
if (bundle != null) {
ArrayList<User> userList = (ArrayList<User>) bundle.getSerializable("myUser");
if (userList != null && !userList.isEmpty()) {
User user = userList.get(0);
String info = "Tên: " + user.getName() + "\nTuổi: " + user.getAge() + "\nThành phố: " + user.getCity();
TextView tvName = findViewById(R.id.textView);
tvName.setText(info);
}
}
}
}
Bước 7: Khai báo Activity trong Manifest
<?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>
Lưu ý quan trọng
- Serializable dễ sử dụng nhưng hiệu suất kém hơn Parcelable (được tối ưu cho Android). Với dữ liệu lớn, khuyến nghị dùng Parcelable.
- Giới hạn kích thước Intent/Bundle khoảng 1MB. Nếu dữ liệu quá lớn, hãy dùng
ViewModel(chia sẻ quaViewModelProvider),Room Database, hoặcFile/SharedPreferences. - Tất cả các trường trong class
Usercũng phải Serializable (các kiểu primitive, String, List<Serializable> đều được hỗ trợ).