Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

difference between bundle and parcelable

Tags:

java

android

So I've been studying about passing data between activities and I found out there are three ways:

1) direct from Intent

2) Parcelable

3) Bundle

What is the difference between Parcelable and Bundle? When should we use each?


1 Answers

  1. Parcelable is an interface to be implemented by some model class. If class implements Parcelable then instances of this class can be serialized and deserialized from a Parcel. Parcelable is an effective android analogue of java Serializable interface.

Example of implemeting Parcelable:

data class User(val id: Long, val email: String?) : Parcelable {

    constructor(parcel: Parcel) : this(
            parcel.readLong(),
            parcel.readString()) {
    }

    override fun writeToParcel(dest: Parcel, flags: Int) {
        dest.writeLong(id)
        dest.writeString(email)
    }

    override fun describeContents(): Int = 0

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

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

Also in kotlin there is @Parcelize annotation which simplifies the process in most cases:

@Parcelize
data class User(val id: Long, val email: String?) : Parcelable
  1. Bundle is a container for named values of types standard for android (including Parcelable), which is used to pass data between activies, fragments and other android app entites.

    val user = User(1L, "[email protected]")
    val bundle = Bundle().apply {
        putLong("userId", user.id)
        putString("userEmail", user.email)
        putParcelable("user", user)
    }
    
    val userId = bundle.getLong("userId")
    val userEmail = bundle.getString("userEmail")
    val user1: User? = bundle.getParcelable("user")
    
like image 112
art Avatar answered Sep 21 '25 04:09

art