Android Kotlin create class implement Parcelable give an error in 'override' of writeToParcel method
Asked Answered
H

2

14

To use Parcelable, I had followed this release of Kotlin 1.1.4 : https://blog.jetbrains.com/kotlin/2017/08/kotlin-1-1-4-is-out/

Add this line in project

androidExtensions {
    experimental = true
}

Then define a class :

@Parcelize
class User(val firstName: String, val lastName: String) : Parcelable

The writeToParcel() and createFromParcel() methods are created automatically

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

but still have an error in 'override' keyword with message

OVERRIDING_WRITE_TO_PARCEL_IS_NOT_ALLOWED: Overriding 'writeToParcel' is not allowed. Use 'Parceler' companion object instead

Can you show me the right way?

Edit : Does only properties defined in default constructor will be add to Parcel, and other is not? I see this warning in this class.

PROPERTY_WONT_BE_SERIALIZED: Property would not be serialized into a 'Parcel'. Add '@Transient' annotation to remove the warning

Horary answered 7/9, 2017 at 9:55 Comment(0)
S
9

Make sure you are using the kotlin 1.1.4 version

No need to override the writeToParcel/createFromParcel methods. Unless you doing any specific things.The studio gives you error but you can ignore this error; the lint checks haven’t yet been updated to understand @Parcelize. The corresponding YouTrack issue is here:

https://youtrack.jetbrains.com/issue/KT-19300

To use create class

enter image description here

Then to pass it like

enter image description here

To get it back

enter image description here

Smalls answered 7/9, 2017 at 13:4 Comment(2)
If I define a child class which inherit parcelable class. Do I need to add Parcelize annotation?Horary
I never tried this but if you want to serialize the child class use Parcelize at child class instead of base class.and if not serializing the child class then no need to Parcelize.what do you want to achieve?Smalls
N
5

You can safely just ignore the warning as it's only lint check.
for now to get rid of it just use @SuppressLint("ParcelCreator")

ex:

@SuppressLint("ParcelCreator")
@Parcelize
class User(val firstName: String, val lastName: String) : Parcelable
Nureyev answered 7/9, 2017 at 20:47 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.