Adel Karshenas
Adel Karshenas

Reputation: 11

Parcelable in Kotlin

When I auto Parcelable my class parcel.readString() and parcel.readString() are underlined red even though my variables are in String format . Here is my code

import android.os.Parcel
import android.os.Parcelable

class adel constructor(var lel : String, var skl: String) : Parcelable {
    constructor(parcel: Parcel) : this(
             parcel.readString(),
             parcel.readString()
         ) {}

    override fun writeToParcel(parcel: Parcel, flags: Int) {
        parcel.writeString(lel)
        parcel.writeString(skl)
    }

    override fun describeContents(): Int {
        return 0
    }

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

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

Upvotes: 0

Views: 358

Answers (2)

apksherlock
apksherlock

Reputation: 8371

Since you are in Kotlin, you can skip the implementation and instead install a nice feature. Just add this in build.gradle:

androidExtensions {
        experimental = true
    }

Then in you class:

import kotlinx.android.parcel.Parcelize   

@Parcelize
data class Adel(var lel : String, var skl: String) : Parcelable

And you are done. Note that you will have a lint error. Just ignore it.

Upvotes: 4

Francesc
Francesc

Reputation: 29380

parcel.readString()

is nullable, replace with

parcel.readString().orEmpty()

Upvotes: 1

Related Questions