Home > Back-end >  Pass data from an arraylist containing a card list
Pass data from an arraylist containing a card list

Time:12-22

Tell me how or how best to transfer the Card data contained in the CardList array (ArrayList)?
data class Card:

data class Card(
val id: Long,
val category: String,
val company: String,
val name: String,
val cost: Int,
val photo: String)

List of cards:

var cardList = ArrayList<Card>()
    ...
cardList = (1..50).map {
    val card = Card(
        id = it.toLong(),
        category = faker.name().name(),
        company = faker.company().name(),
        name = faker.name().name(),
        cost = it,
        photo = "https://images.unsplash.com/photo........"
    )
    adapter.addCard(card)
} as ArrayList<Card>

And there is a ProductActivity class, which should, based on the transmitted data from CardList, substitute these values in the view. The main task, there are card elements on recyclerview (an array of 50 pieces), each of them has its own id, string values and photo images, that is, data class Card values, you need to transfer these values to ProductActivity (when you click on the card element from recyclerview, activity opens) and in this window display the data transferred from CardList (data class Card values)

CodePudding user response:

Make your data-class Parcelable, Add plugin in build.gradle(app)

plugins {
    ...
    id 'kotlin-parcelize'
}

Make your data-class Parcelable,

@Parcelize
data class Card (
    val id: Long,
    val category: String,
    val company: String,
    val name: String,
    val cost: Int,
    val photo: String
) : Parcelable

In your onItemClick, pass this object via intent extras

itemView.setOnClickListener(()-> {
    val intent = Intent(this, SecondActivity::class.java)
    intent.putExtra("item", card)
    startActivity(intent)
}

In other activity,

val card : Card = getIntent().getParcelableExtra("item")
  • Related