首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計綜合問答

Android 購物車實現:商品數據傳遞到結算頁的三種方案對比

     編輯:程式設計綜合問答

場景描述

商品列表頁(ListView/RecyclerView)已通過 JSON 解析填充數據,每項含「加入購物車」按鈕。點擊後需將選中商品信息傳遞到購物車/結算 Activity 顯示。

三種主流傳遞方案對比

方案核心機制優點缺點適用場景
1. Intent + Bundle/Parcelable (推薦) 序列化對象放入 Bundle → putExtra → startActivity 標準、進程隔離安全、支持進程間通信、生命周期受系統管理 數據量大時受 Binder 限制(~1MB)、需實現 Parcelable/Serializable 大多數場景,特別是跨 Activity/進程
2. 單例/靜態持有類 全局靜態 Map/List 保存數據,目標頁直接讀取 代碼極簡、無大小限制、跨任意組件訪問 內存洩漏風險、進程重啟數據丟失、線程不安全、耦合度高、難測試 極簡原型、臨時數據、單進程小應用
3. 本地持久化 Room/SQLite/SharedPreferences/File 存儲,傳遞 ID 查詢 數據持久化、跨進程/重啟可用、支持複雜查詢 IO 開銷、代碼量大、需處理同步/遷移 購物車需持久化、多端同步、離線可用

方案一 代碼實現(Parcelable + Intent)

1. 實體類實現 Parcelable (Kotlin 推薦 @Parcelize)

// Java 版
public class Goods implements Parcelable {
    private long id;
    private String name;
    private double price;
    private int count;
    // getter/setter/構造器
    
    protected Goods(Parcel in) {
        id = in.readLong();
        name = in.readString();
        price = in.readDouble();
        count = in.readInt();
    }
    public static final Creator CREATOR = new Creator() {
        @Override public Goods createFromParcel(Parcel in) { return new Goods(in); }
        @Override public Goods[] newArray(int size) { return new Goods[size]; }
    };
    @Override public void writeToParcel(Parcel dest, int flags) {
        dest.writeLong(id);
        dest.writeString(name);
        dest.writeDouble(price);
        dest.writeInt(count);
    }
    @Override public int describeContents() { return 0; }
}

// Kotlin 版 (一行搞定)
@Parcelize
data class Goods(
    val id: Long,
    val name: String,
    val price: Double,
    var count: Int
) : Parcelable

2. 列表頁發送

// 單個商品
Intent intent = new Intent(this, CartActivity.class);
intent.putExtra("goods", goods); // Parcelable 自動打包
startActivity(intent);

// 多個商品 (ArrayList)
intent.putParcelableArrayListExtra("goodsList", selectedGoodsList);

3. 結算頁接收

Goods goods = getIntent().getParcelableExtra("goods");
ArrayList list = getIntent().getParcelableArrayListExtra("goodsList");

進階:購物車數據管理架構

// 單例管理器 (應用級)
public class CartManager {
    private static CartManager instance;
    private final Map cartMap = new ConcurrentHashMap<>();
    
    public static CartManager get() { ... }
    
    public void addGoods(Goods goods) { ... }
    public List getAllGoods() { ... }
    public void syncToLocal() { ... } // 異步持久化到 Room/SP
}
  • UI 層通過 CartManager.get().addGoods() 操作;
  • 結算頁直接讀取 CartManager.get().getAllGoods() 或接收 Intent 數據;
  • 關鍵節點(加入、結算、登出)調用 syncToLocal() 落地;
  • 啟動時從本地恢復 CartManager 狀態。

總結建議

  1. 首選 Intent + Parcelable:Android 官方標準,安全可靠,代碼量可接受(Kotlin @Parcelize 極簡);
  2. 輔以 CartManager 單例:作為內存數據權威源,UI 監聽其變化(LiveData/Flow/RxBus)自動刷新;
  3. 異步持久化 Room:保障進程殺死/重啟數據不丟,啟動時恢復;
  4. 避免純靜態 Map 直接傳遞:內存洩漏、進程隔離失效、難以擴展。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved