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?
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
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")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With