You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何传递Parcelable对象?附CheckoutResponseMdl数据类代码

How to Pass Parcelable Objects in Android (With Your CheckoutResponseMdl Example)

Got it, let's walk through how to properly implement Parcelable for your CheckoutResponseMdl and how to pass it between Android components. First, your current code has placeholders and missing pieces—let's fix that, plus remember: your nested ItemsCheckout class also needs to implement Parcelable to work correctly.

Step 1: Fix the Parcelable Implementation

First, let's define a complete ItemsCheckout (adjust fields to match your actual data):

data class ItemsCheckout(
    val itemId: String,
    val quantity: Int,
    val totalPrice: Double
) : Parcelable {
    // Parcel constructor to deserialize the object
    constructor(parcel: Parcel) : this(
        parcel.readString() ?: "",
        parcel.readInt(),
        parcel.readDouble()
    )

    override fun writeToParcel(parcel: Parcel, flags: Int) {
        // Serialize each field to the parcel
        parcel.writeString(itemId)
        parcel.writeInt(quantity)
        parcel.writeDouble(totalPrice)
    }

    override fun describeContents(): Int {
        return 0 // Use 0 unless you're working with file descriptors
    }

    companion object CREATOR : Parcelable.Creator<ItemsCheckout> {
        override fun createFromParcel(parcel: Parcel): ItemsCheckout {
            return ItemsCheckout(parcel)
        }

        override fun newArray(size: Int): Array<ItemsCheckout?> {
            return arrayOfNulls(size)
        }
    }
}

Now update your CheckoutResponseMdl to handle the nested ItemsCheckout correctly:

data class CheckoutResponseMdl(val items: ItemsCheckout) : Parcelable {
    // Parcel constructor to read the nested ItemsCheckout
    constructor(parcel: Parcel) : this(
        parcel.readParcelable(ItemsCheckout::class.java.classLoader) ?:
        throw IllegalArgumentException("ItemsCheckout cannot be null")
    )

    override fun writeToParcel(parcel: Parcel, flags: Int) {
        // Write the entire ItemsCheckout object to the parcel
        parcel.writeParcelable(items, flags)
    }

    override fun describeContents(): Int {
        return 0
    }

    companion object CREATOR : Parcelable.Creator<CheckoutResponseMdl> {
        override fun createFromParcel(parcel: Parcel): CheckoutResponseMdl {
            return CheckoutResponseMdl(parcel)
        }

        override fun newArray(size: Int): Array<CheckoutResponseMdl?> {
            return arrayOfNulls(size)
        }
    }
}

Key Notes

  • For nested Parcelable objects, use parcel.writeParcelable() to serialize and parcel.readParcelable() to deserialize (don’t forget the class loader).
  • Add null checks based on whether your fields can be null in your actual use case.

Step 2: Pass the Parcelable Object

Option 1: Between Activities (Using Intent)

// In your source Activity
val checkoutData = CheckoutResponseMdl(ItemsCheckout("shirt_001", 2, 59.98))
val intent = Intent(this, TargetActivity::class.java)
intent.putExtra("CHECKOUT_DATA", checkoutData)
startActivity(intent)

Option 2: Between Fragments (Using Bundle)

// In your source Fragment
val checkoutData = CheckoutResponseMdl(ItemsCheckout("shirt_001", 2, 59.98))
val targetFragment = TargetFragment()
val bundle = Bundle()
bundle.putParcelable("CHECKOUT_DATA", checkoutData)
targetFragment.arguments = bundle

// Perform the fragment transaction
supportFragmentManager.beginTransaction()
    .replace(R.id.fragment_container, targetFragment)
    .commit()

Step 3: Receive the Parcelable Object

In the Target Activity

// In onCreate()
val checkoutResponse = intent.getParcelableExtra<CheckoutResponseMdl>("CHECKOUT_DATA")
checkoutResponse?.let {
    // Use the data, e.g.:
    println("Item ID: ${it.items.itemId}, Quantity: ${it.items.quantity}")
}

In the Target Fragment

// In onCreateView() or onCreate()
val checkoutResponse = arguments?.getParcelable<CheckoutResponseMdl>("CHECKOUT_DATA")
checkoutResponse?.let {
    // Work with the deserialized data
}

Bonus: Simplify with Kotlin's @Parcelize

For Kotlin projects, you can skip all the boilerplate using the kotlin-parcelize plugin:

  1. Add the plugin to your app-level build.gradle:
plugins {
    id 'kotlin-parcelize'
}
  1. Rewrite your classes with the @Parcelize annotation:
import kotlinx.parcelize.Parcelize

@Parcelize
data class ItemsCheckout(
    val itemId: String,
    val quantity: Int,
    val totalPrice: Double
) : Parcelable

@Parcelize
data class CheckoutResponseMdl(val items: ItemsCheckout) : Parcelable

That's it—no need to write constructors, writeToParcel, or CREATOR methods. This is the cleanest approach for Kotlin.


内容的提问来源于stack exchange,提问作者Vanya Rachel

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 06:28:55