First of all, you have to make sure SongInfo
has implemented Parcelable
like code below
data class SongInfo(
var title: String? = null,
var authorName: String? = null,
var songURL: String? = null
) : Parcelable {
constructor(parcel: Parcel) : this(
parcel.readString(),
parcel.readString(),
parcel.readString())
override fun writeToParcel(parcel: Parcel, flags: Int) {
parcel.writeString(title)
parcel.writeString(authorName)
parcel.writeString(songURL)
}
override fun describeContents(): Int {
return 0
}
companion object CREATOR : Parcelable.Creator<SongInfo> {
override fun createFromParcel(parcel: Parcel): SongInfo {
return SongInfo(parcel)
}
override fun newArray(size: Int): Array<SongInfo?> {
return arrayOfNulls(size)
}
}
}
After that, the code in the first activity should be similar to this
class ActivityOne: AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?, persistentState: PersistableBundle?) {
super.onCreate(savedInstanceState, persistentState)
val button = Button(this) // Just for an example
val arrayList = arrayListOf(
SongInfo("Love yourself", "Justin Bieber", "https://example.com"),
SongInfo("Love yourself", "Justin Bieber", "https://example.com"),
SongInfo("Love yourself", "Justin Bieber", "https://example.com"),
SongInfo("Love yourself", "Justin Bieber", "https://example.com")
)
button.setOnClickListener {
val intent = Intent(applicationContext, ActivityTwo::class.java)
intent.putExtra("songs", arrayList)
startActivity(intent)
}
}
}
And then in order to receive your array list from the first activity you need to parse it by using getParcelableArrayListExtra<SongInfo>(..)
method.
class ActivityTwo: AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
val songs = intent?.getParcelableArrayListExtra<SongInfo>("songs") ?:
throw IllegalStateException("Songs array list is null")
println(songs) // There you go
}
}
Android Studio could help you create a boilerplate code of Parcelable
as well by Option + return
on Mac.