Reputation: 3439
I'm currently using the excellent AutoParcel in my Java project, which facilitates the creation of Parcelable classes.
Now, Kotlin, which I consider for my next project, has this concept of data classes, that automatically generate the equals, hashCode and toString methods.
Is there a convenient way to make a Kotlin data class Parcelable in a convenient way (without implementing the methods manually)?
Upvotes: 177
Views: 118902
Reputation: 36
Since nobody has mentioned this point ( Or rather, not provided specific detail on versions), I am going comment real quick on this:
I tried all the possible combinations of @Parcelize
using the above guidance, but was not successful in getting it to work.
If your Android studio shows error on your class that describeContents
or writeToParcel
is not implemented, even with the @Parcelize
annotation, please check that in your app/build.gradle
you don't have apply plugin: 'kotlin-android-extensions'
enabled.
This is not working. For some reason, my project was using older deprecated version of extensions (ktxVersion = '1.0.2').
So this was conflicting with the @Parcelize
implementation.
When I tried to add apply plugin: 'kotlin-parcelize'
, it said it's not going to work with the extensions simultaneously and I can have only one or the other.
After working with a colleague, we figured out that the extension was causing the whole @Parcelize
to fail. I tried so many different things, but even after getting over the compile time errors, runtime error would say "CREATOR" not found exception or similar.
So finally I removed the apply plugin for kotlin-android-extensions
and just included the apply plugin: 'kotlin-parcelize'
, which fixed that issue, and it works as expected.
Upvotes: 0
Reputation: 1212
A simpler and up-to-date method would be to use the @Parcelize
annotation which removes the hard word work of implementing the Parcelable
build.gradle (app module)
apply plugin: "kotlin-parcelize"
// If you are using the new plugin format use this instead.
plugins{
...
id "kotlin-parcelize"
}
YourClass.kt
import kotlinx.parcelize
@Parcelize
class User(val firstName: String, val lastName: String, val age: Int): Parcelable
Upvotes: 32
Reputation: 2687
Below Kotlin code can help you to create Parcelable data classes with Parent and Child Data class
Parent Data Class - MyPostModel
data class MyPostModel(
@SerializedName("post_id") val post_id: String? = "",
@SerializedName("category_id") val category_id: String? = "",
@SerializedName("images") val images: ArrayList<ImagesModel>? = null
) : Parcelable {
constructor(parcel: Parcel) : this(
parcel.readString(),
parcel.readString(),
parcel.createTypedArrayList(ImagesModel.CREATOR)
)
override fun writeToParcel(parcel: Parcel, flags: Int) {
parcel.writeString(post_id)
parcel.writeString(category_id)
parcel.writeTypedList(images)
}
override fun describeContents(): Int {
return 0
}
companion object CREATOR : Parcelable.Creator<MyPostModel> {
override fun createFromParcel(parcel: Parcel): MyPostModel {
return MyPostModel(parcel)
}
override fun newArray(size: Int): Array<MyPostModel?> {
return arrayOfNulls(size)
}
}
}
Child Data Class - ImagesModel
data class ImagesModel(
@SerializedName("image_id") val image_id: String? = "",
@SerializedName("image_url") val image_url: String? = ""
) : Parcelable {
constructor(parcel: Parcel) : this(
parcel.readString(),
parcel.readString()
)
override fun writeToParcel(parcel: Parcel, flags: Int) {
parcel.writeString(image_id)
parcel.writeString(image_url)
}
override fun describeContents(): Int {
return 0
}
companion object CREATOR : Parcelable.Creator<ImagesModel> {
override fun createFromParcel(parcel: Parcel): ImagesModel {
return ImagesModel(parcel)
}
override fun newArray(size: Int): Array<ImagesModel?> {
return arrayOfNulls(size)
}
}
}
Upvotes: 3
Reputation: 7070
You can do it using @Parcelize
annotation. It is an automatic Parcelable implementation generator.
First, you need to enable them adding this to your module's build.gradle:
apply plugin: 'org.jetbrains.kotlin.android.extensions'
Declare the serialized properties in a primary constructor and add a @Parcelize
annotation, and writeToParcel()
/createFromParcel()
methods will be created automatically:
@Parcelize
class User(val firstName: String, val lastName: String) : Parcelable
You DONT need to add experimental = true
inside androidExtensions
block.
Upvotes: 5
Reputation: 617
Example :
@Parcelize
data class Item(
var imageUrl: String,
var title: String,
var description: Category
) : Parcelable
Upvotes: 21
Reputation: 9697
Kotlin 1.1.4 is out
Android Extensions plugin now includes an automatic Parcelable implementation generator. Declare the serialized properties in a primary constructor and add a @Parcelize annotation, and writeToParcel()/createFromParcel() methods will be created automatically:
@Parcelize
class User(val firstName: String, val lastName: String) : Parcelable
So you need to enable them adding this to you module's build.gradle:
apply plugin: 'org.jetbrains.kotlin.android.extensions'
android {
androidExtensions {
experimental = true
}
}
Upvotes: 272
Reputation: 1578
Kotlin has made the entire process of Parcelization in Android damn easy with its @Parcel annotation.
To do that
Step 1. Add Kotlin extensions in your app module gradle
Step 2. Add experimental = true since this feature is still in experimentation in gradle.
androidExtensions { experimental = true }
Step 3. Annonate the data class with @Parcel
Here is an simple example on @Parcel usage
Upvotes: 1
Reputation: 4477
Just click on the data keyword of your kotlin data class, then press alt+Enter, select the first option saying "Add Parceable Implementation"
Upvotes: 37
Reputation: 4851
The best way with no boilerplate code at all is Smuggler gradle plugin. All you need is just implement AutoParcelable interface like
data class Person(val name:String, val age:Int): AutoParcelable
And that's all. Works for sealed classes as well. Also this plugin provides compile time validation for all AutoParcelable classes.
UPD 17.08.2017 Now with Kotlin 1.1.4 and Kotlin Android extensions plugin you could use @Parcelize
annotation. In this case, the example above will look like:
@Parcelize class Person(val name:String, val age:Int): Parcelable
No need for data
modifier. The biggest downside, for now, is using kotlin-android-extensions plugin which has a lot of other functions that could be unnecessary.
Upvotes: 17
Reputation: 2427
Using Android Studio and the Kotlin plugin, I found an easy way to convert my old Java Parcelable
s with no extra plugins (if all you want is to turn a brand new data
class into a Parcelable
, skip to the 4th code snippet).
Let's say you have a Person
class with all the Parcelable
boiler plate:
public class Person implements Parcelable{
public static final Creator<Person> CREATOR = new Creator<Person>() {
@Override
public Person createFromParcel(Parcel in) {
return new Person(in);
}
@Override
public Person[] newArray(int size) {
return new Person[size];
}
};
private final String firstName;
private final String lastName;
private final int age;
public Person(String firstName, String lastName, int age) {
this.firstName = firstName;
this.lastName = lastName;
this.age = age;
}
protected Person(Parcel in) {
firstName = in.readString();
lastName = in.readString();
age = in.readInt();
}
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(firstName);
dest.writeString(lastName);
dest.writeInt(age);
}
@Override
public int describeContents() {
return 0;
}
public String getFirstName() {
return firstName;
}
public String getLastName() {
return lastName;
}
public int getAge() {
return age;
}
}
Start by stripping out the Parcelable
implementation, leaving a bare-bones, plain, old Java object (properties should be final and set by the constructor):
public class Person {
private final String firstName;
private final String lastName;
private final int age;
public Person(String firstName, String lastName, int age) {
this.firstName = firstName;
this.lastName = lastName;
this.age = age;
}
public String getFirstName() {
return firstName;
}
public String getLastName() {
return lastName;
}
public int getAge() {
return age;
}
}
Then let the Code > Convert Java file to Kotlin File
option do its magic:
class Person(val firstName: String, val lastName: String, val age: Int)
Convert this into a data
class:
data class Person(val firstName: String, val lastName: String, val age: Int)
And finally, let's turn this into a Parcelable
again. Hover the class name and Android Studio should give you the option to Add Parcelable Implementation
. The result should look like this:
data class Person(val firstName: String, val lastName: String, val age: Int) : Parcelable {
constructor(parcel: Parcel) : this(
parcel.readString(),
parcel.readString(),
parcel.readInt()
)
override fun writeToParcel(parcel: Parcel, flags: Int) {
parcel.writeString(firstName)
parcel.writeString(lastName)
parcel.writeInt(age)
}
override fun describeContents(): Int {
return 0
}
companion object CREATOR : Parcelable.Creator<Person> {
override fun createFromParcel(parcel: Parcel): Person {
return Person(parcel)
}
override fun newArray(size: Int): Array<Person?> {
return arrayOfNulls(size)
}
}
}
As you can see, the Parcelable
implementation is some auto-generated code appended to you data
class definition.
Notes:
Parcelable
directly into Kotlin will not produce the same result with the current version of the Kotlin plugin (1.1.3
).Parcelable
code generator introduces. Must be a minor bug. I hope this tip works for you as well as it did for me.
Upvotes: 6
Reputation: 398
i prefer just using the https://github.com/johncarl81/parceler lib with
@Parcel(Parcel.Serialization.BEAN)
data class MyClass(val value)
Upvotes: 2
Reputation: 9818
Have you tried PaperParcel? It's an annotation processor which automatically generates the Android Parcelable
boilerplate code for you.
Usage:
Annotate your data class with @PaperParcel
, implement PaperParcelable
, and add a JVM static instance of the generated CREATOR
e.g.:
@PaperParcel
data class Example(
val test: Int,
...
) : PaperParcelable {
companion object {
@JvmField val CREATOR = PaperParcelExample.CREATOR
}
}
Now your data class is Parcelable
and can be passed directly to a Bundle
or Intent
Edit: Update with latest API
Upvotes: 18
Reputation: 1210
I will leave my way of doing in case it might help someone.
What i do is i have a generic Parcelable
interface DefaultParcelable : Parcelable {
override fun describeContents(): Int = 0
companion object {
fun <T> generateCreator(create: (source: Parcel) -> T): Parcelable.Creator<T> = object: Parcelable.Creator<T> {
override fun createFromParcel(source: Parcel): T = create(source)
override fun newArray(size: Int): Array<out T>? = newArray(size)
}
}
}
inline fun <reified T> Parcel.read(): T = readValue(T::class.javaClass.classLoader) as T
fun Parcel.write(vararg values: Any?) = values.forEach { writeValue(it) }
And then i create parcelables like this:
data class MyParcelable(val data1: Data1, val data2: Data2) : DefaultParcelable {
override fun writeToParcel(dest: Parcel, flags: Int) { dest.write(data1, data2) }
companion object { @JvmField final val CREATOR = DefaultParcelable.generateCreator { MyParcelable(it.read(), it.read()) } }
}
Which gets me rid of that boilerplate override.
Upvotes: 5
Reputation: 7711
There is a Plugin but is not always as updated as Kotlin is evolving: https://plugins.jetbrains.com/plugin/8086
Alternative:
I have a working example of a custom data class using Parcelable
and lists:
Data classes using Parcelable with Lists:
Hope it helps!
Upvotes: 0
Reputation: 539
You can try this plugin:
android-parcelable-intellij-plugin-kotlin
It help you generate Android Parcelable boilerplate code for kotlin's data class. And it finally look like this:
data class Model(var test1: Int, var test2: Int): Parcelable {
constructor(source: Parcel): this(source.readInt(), source.readInt())
override fun describeContents(): Int {
return 0
}
override fun writeToParcel(dest: Parcel?, flags: Int) {
dest?.writeInt(this.test1)
dest?.writeInt(this.test2)
}
companion object {
@JvmField final val CREATOR: Parcelable.Creator<Model> = object : Parcelable.Creator<Model> {
override fun createFromParcel(source: Parcel): Model{
return Model(source)
}
override fun newArray(size: Int): Array<Model?> {
return arrayOfNulls(size)
}
}
}
}
Upvotes: 53
Reputation: 33829
Unfortunately there is no way in Kotlin to put a real field in an interface, so you can't inherit it from an interface-adapter for free:
data class Par : MyParcelable
You may look at delegation, but it does not help with fields, AFAIK: https://kotlinlang.org/docs/reference/delegation.html
So the the only option I see is a fabric function for Parcelable.Creator
, which is kind of obvious.
Upvotes: 3