Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.7k 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 Reply

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)
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...