Search code examples
androidkotlinnullableparcelabletype-mismatch

Android parcelable - write nullable long


I have my parcelable class Article:

class Article : Parcelable {

    var image: Long? = null
    var category: String? = null
    var videos: String? = null

    constructor(data: JSONObject) {
        if (condition) image = 50000L
        category = data.getString("category")
        videos = data.getString("videos")
    }

    private constructor(parcel: Parcel) {
        image = parcel.readLong()
        category = parcel.readString()
        videos = parcel.readString()
    }

    override fun writeToParcel(dest: Parcel, flags: Int) {
        dest.writeLong(image) // error here
        dest.writeString(category)
        dest.writeString(videos)
    }

    override fun describeContents(): Int = 0

    companion object {
        @JvmField val CREATOR: Parcelable.Creator<Article> = object : Parcelable.Creator<Article> {
            override fun createFromParcel(parcel: Parcel): Article = Article(parcel)
            override fun newArray(size: Int): Array<Article?> = arrayOfNulls(size)
        }
    }
}

But my class is getting a type mismatch at writing the image var. It is expecting a Long and not a Long?. I do understand that this could be solved if I do something like this:

dest.writeLong(image!!)

But the problem is that this var could really be null on my context. I don't want either to define my image var as a default value like 0. I really want the var to remain nullable.

Is there any way to write a nullable var?


Solution

  • If your image variable should keep nullable

    parcel.readValue(Long::class.java.classLoader) as? Long

    parcel.writeValue(image)