Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.5k views
in Technique[技术] by (71.8m points)

kotlin - how to read Int arraylist in parcelable in android

I am making a data class for Parcelable. but unable to find out a solution that, how to read integer ArrayList in Parcelable class in kotlin. I know about String, but I face a problem in the Int type ArrayList.

var priceDetail: ArrayList<Int?>?,

for more detail see this,

    data class PostCardsListData(
        var arrDescriptionsTags: ArrayList<String?>?,
        var priceDetail: ArrayList<Int?>?,
..........

: Parcelable {
    constructor(parcel: Parcel) : this(
        parcel.createStringArrayList(), // i know about string
        //but how to read this Integer arraylist
        

this is my full data class code

import android.os.Parcel
import android.os.Parcelable
data class PostCardsListData(
    var arrDescriptionsTags: ArrayList<String?>?,
    var priceDetail: ArrayList<Int?>?,

) : Parcelable {
    constructor(parcel: Parcel) : this(
        parcel.createStringArrayList(),
        parcel.//describe me what i will write here

    )

    override fun writeToParcel(parcel: Parcel, flags: Int) {
        parcel.writeStringList(arrDescriptionsTags)
        parcel.write//describe me what i will write here
    }

    override fun describeContents(): Int {
        return 0
    }

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

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

So to create a parcelable class.

Firstly, Add add plugin to the gradle

plugins {
    .
    .
    id 'kotlin-parcelize'
}

Then, create a class and use annotations to parcelize the data

@Parcelize
class PostCardsListData(

    @SerializedName("arrDescriptionsTags")
    var arrDescriptionsTags: ArrayList<String>? = null,

    @SerializedName("priceDetail")
    var priceDetail: ArrayList<Int?>? = null

) : Parcelable 

To read/write data you just need to create an object of this class and use the dot operator to access the list.

In the activity/fragment/viewModel class

private var listData = PostCardsListData()

//read data

private var priceList : ArrayList<Int> = ArrayList()
if(listData.priceDetail != null){
    priceList.addAll(listData.priceDetail)
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...