How to Implement Parcelable In Kotlin For Android Development?

11 minutes read

To implement Parcelable in Kotlin for Android development, follow these steps:

  1. Open your Kotlin data class or model class that you want to make Parcelable.
  2. Add the Parcelable interface to your class declaration: data class ExampleModel(...) : Parcelable { // class implementation }
  3. Implement the required Parcelable methods: describeContents() and writeToParcel(). Use the following code snippet as a reference and modify it according to your class attributes: data class ExampleModel(...) : Parcelable { // class implementation override fun writeToParcel(parcel: Parcel, flags: Int) { // Write class attributes to the parcel parcel.write...(...) } override fun describeContents(): Int { return 0 } companion object CREATOR : Parcelable.Creator { override fun createFromParcel(parcel: Parcel): ExampleModel { return ExampleModel(parcel) } override fun newArray(size: Int): Array { return arrayOfNulls(size) } } }
  4. Inside the writeToParcel() method, write your class attributes to the parcel using appropriate methods like writeInt(), writeString(), writeParcelable(), etc. Ensure that you write/read the attributes in the same order in which they were declared.
  5. Inside the createFromParcel() constructor of the companion object, retrieve the attributes from the parcel and create a new instance of your class.
  6. After implementing the Parcelable interface, check if there are any additional classes in your model that also need to be made Parcelable. If yes, repeat steps 2-5 for those classes.
  7. Now, you can pass instances of your model class between activities or fragments using intents or bundles without any issues.


Remember to keep the Parcelable implementation up-to-date whenever you make changes to your class attributes.


That's it! You have successfully implemented Parcelable in Kotlin for Android development.

Best Kotlin Books to Read in 2024

1
Atomic Kotlin

Rating is 5 out of 5

Atomic Kotlin

2
Kotlin in Action

Rating is 4.9 out of 5

Kotlin in Action

3
Head First Kotlin: A Brain-Friendly Guide

Rating is 4.8 out of 5

Head First Kotlin: A Brain-Friendly Guide

4
Kotlin Programming: The Big Nerd Ranch Guide (Big Nerd Ranch Guides)

Rating is 4.7 out of 5

Kotlin Programming: The Big Nerd Ranch Guide (Big Nerd Ranch Guides)

5
Kotlin Cookbook: A Problem-Focused Approach

Rating is 4.6 out of 5

Kotlin Cookbook: A Problem-Focused Approach

6
Java to Kotlin: A Refactoring Guidebook

Rating is 4.5 out of 5

Java to Kotlin: A Refactoring Guidebook

7
Programming Kotlin: Create Elegant, Expressive, and Performant JVM and Android Applications

Rating is 4.4 out of 5

Programming Kotlin: Create Elegant, Expressive, and Performant JVM and Android Applications

8
Advanced Kotlin (Kotlin for Developers Book 4)

Rating is 4.3 out of 5

Advanced Kotlin (Kotlin for Developers Book 4)


How to make a class Parcelable in Kotlin?

To make a class Parcelable in Kotlin, follow these steps:

  1. Add the androidx.parcelable.Parcelize annotation to your class. This annotation is part of the kotlinx.android.parcel library, which provides Parcelable support for Kotlin classes.
1
2
3
4
5
6
import androidx.parcelize.Parcelize

@Parcelize
class MyClass(val name: String, val age: Int) : Parcelable {
    // Class implementation goes here
}


  1. Make sure your class implements the android.os.Parcelable interface.
  2. Remove the boilerplate code for implementing Parcelable. Since Kotlin provides type inference, you don't need to define the CREATOR object manually. Parcelize annotation does that for you.


That's it! Your class is now Parcelable. You can use it to pass objects between activities, fragments, or any other components that support Parcelable data.


How to read Parcelable data from a Parcel in Kotlin?

In order to read Parcelable data from a Parcel in Kotlin, you can follow these steps:

  1. Implement the Parcelable interface in your data class to define how the object should be serialized and deserialized.
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
data class ExampleParcelable(val name: String, val age: Int) : Parcelable {
    constructor(parcel: Parcel) : this(
        parcel.readString().toString(),
        parcel.readInt()
    )

    override fun writeToParcel(parcel: Parcel, flags: Int) {
        parcel.writeString(name)
        parcel.writeInt(age)
    }

    override fun describeContents(): Int {
        return 0
    }

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

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


  1. In your receiving class (e.g., an Activity or Fragment), retrieve the Parcelable object from the Intent or arguments bundle.
1
val exampleParcelable = intent.getParcelableExtra<ExampleParcelable>("EXAMPLE_PARCELABLE_KEY")


  1. Use the retrieved object as desired.
1
println("Name: ${exampleParcelable.name}, Age: ${exampleParcelable.age}")


Note: Replace "EXAMPLE_PARCELABLE_KEY" with the key you used to put the Parcelable object into the Intent or arguments bundle.


That's it! You have successfully read Parcelable data from a Parcel in Kotlin.


What is the Parcelable interface in Kotlin?

The Parcelable interface is used in Kotlin to allow objects to be serialized and deserialized easily. It provides a way to pass objects between different components within an Android application or even between different applications. By implementing the Parcelable interface, you can convert an object into a stream of bytes to send it over a network or save it into a file, and then recreate the object from the stream of bytes.


In order to make a class parcelable, it needs to implement the Parcelable interface and override a few methods, such as writeToParcel() to write the object's data to a Parcel, and createFromParcel() to recreate the object from a Parcel. Additionally, a Creator object needs to be implemented to create instances of the class from a Parcel.


The Parcelable interface provides a more efficient way to serialize objects compared to the Serializable interface, which is another way to achieve object serialization in Java and Kotlin. Parcelable is optimized for Android and is generally considered faster and more efficient than Serializable.


What is the readParcel() method in Parcelable?

The readParcel() method in Parcelable is a method used to read the contents of the Parcelable object from a Parcel. It is part of the Parcelable interface in Android, which allows an object to be flattened into a byte stream and then reconstructed later. The readParcel() method is responsible for reading the data stored in the Parcel and setting it back in the appropriate fields of the object. This method is typically used when unmarshalling a Parcelable object, for example, when passing objects between different activities or processes in Android.


How to implement Parcelable for custom objects in Kotlin?

To implement Parcelable for custom objects in Kotlin, you need to follow these steps:

  1. Make your class implement the Parcelable interface.
1
2
3
class MyObject(var name: String, var age: Int) : Parcelable {
    // ...
}


  1. Implement the Parcelable.Creator interface within your class companion object.
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
class MyObject(var name: String, var age: Int) : Parcelable {
    // ...

    companion object {
        @JvmField
        val CREATOR: Parcelable.Creator<MyObject> = object : Parcelable.Creator<MyObject> {
            override fun createFromParcel(parcel: Parcel): MyObject {
                return MyObject(parcel)
            }

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


  1. Implement the required methods for the Parcelable interface.
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
class MyObject(var name: String, var age: Int) : Parcelable {
    // ...

    constructor(parcel: Parcel) : this(
        parcel.readString() ?: "",
        parcel.readInt()
    )

    override fun writeToParcel(parcel: Parcel, flags: Int) {
        parcel.writeString(name)
        parcel.writeInt(age)
    }

    override fun describeContents(): Int {
        return 0
    }
}


  1. Make sure to handle the Parcelable.Creator.createFromParcel method in your constructor.


That's it! You have implemented the Parcelable interface for your custom object in Kotlin. Now you can use intent.putExtra or Bundle.putParcelable to pass your custom object between activities or fragments.


How to handle null values in Parcelable objects in Kotlin?

To handle null values in Parcelable objects in Kotlin, you can follow these steps:

  1. Declare your Parcelable class, for example, MyParcelableClass, as usual.
  2. Use the Parcel.writeValue() method to write nullable values to the parcel.
  3. Use the Parcel.readValue() method to read nullable values from the parcel.


Here's an example implementation:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
@Parcelize
data class MyParcelableClass(
    val name: String?,
    val age: Int?
) : Parcelable {
    constructor(parcel: Parcel) : this(
        parcel.readString(),
        parcel.readValue(Int::class.java.classLoader) as? Int
    )

    override fun writeToParcel(parcel: Parcel, flags: Int) {
        parcel.writeString(name)
        parcel.writeValue(age)
    }

    override fun describeContents(): Int {
        return 0
    }

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

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


In the above code, we declare the nullable properties name and age in the MyParcelableClass. The Parcel.writeValue() method writes nullable values to the parcel, and the Parcel.readValue() method reads nullable values from the parcel using the as? operator to handle potential null values.


By following these steps, you can handle null values in Parcelable objects in Kotlin.

Facebook Twitter LinkedIn Whatsapp Pocket

Related Posts:

The Android Kotlin Extensions, also known as KTX, is a library that provides a set of Kotlin extensions for Android development. It aims to simplify Android development by offering concise and idiomatic Kotlin code for common Android tasks.To use the Android K...
To set up a basic Android app using Kotlin, follow these steps:Install Android Studio: Download and install the latest version of Android Studio from the official website. Create a new project: Launch Android Studio and select &#34;Start a new Android Studio p...
Kotlin reflection allows you to inspect and manipulate code at runtime. Although Kotlin is fully compatible with Java, accessing Kotlin&#39;s reflection API from Java requires some extra steps.To use Kotlin reflection in Java, you need to follow these steps:Im...