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

Cách truyền ArrayList giữa các Activity qua Intent trong Android

Giới thiệu

Ví dụ này minh họa cách truyền một ArrayList<String> từ Activity này sang Activity khác thông qua Intent và Serializable.

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: Layout chính (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"
    android:id="@+id/relativeLayout"
    tools:context=".MainActivity">
    <Button
        android:id="@+id/button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Truyền mảng sang Activity 2"
        android:layout_centerInParent="true" />
</RelativeLayout>

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

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

public class MainActivity extends AppCompatActivity {
    Button button;
    ArrayList<String> numbers = new ArrayList<>();

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        
        button = findViewById(R.id.button);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                numbers.add("ONE");
                numbers.add("TWO");
                numbers.add("THREE");
                numbers.add("FOUR");
                numbers.add("FIVE");
                
                Intent intent = new Intent(MainActivity.this, SecondActivity.class);
                intent.putExtra("key", numbers);
                startActivity(intent);
            }
        });
    }
}

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

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

public class SecondActivity extends AppCompatActivity {
    TextView textView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_second);
        
        textView = findViewById(R.id.textView);
        ArrayList<String> numbersList = (ArrayList<String>) getIntent().getSerializableExtra("key");
        textView.setText(String.valueOf(numbersList));
    }
}

Bước 5: Layout Activity 2 (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:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:text=""
        android:textSize="24sp"
        android:textStyle="bold"/>
</RelativeLayout>

Bước 6: Manifest - Đăng ký cả 2 Activity

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="https://schemas.android.com/apk/res/android" package="app.com.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=".SecondActivity"></activity>
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>
</manifest>

Chạy ứng dụng

Kết nối thiết bị, nhấn Run. Nhấn nút để chuyển sang Activity 2 và xem ArrayList được truyền qua.

Cách truyền ArrayList giữa các Activity qua Intent trong Android

Cách truyền ArrayList giữa các Activity qua Intent trong Android

Mẹo: ArrayList implements Serializable nên có thể dùng putExtra/getSerializableExtra. Với object tùy chỉnh, class đó phải implement Serializable.