Pass Object from One Activity to Another using Serializable in Kotlin

The Serializability class allows usable serial integration of the class using the java.io.Serializable interface. To pass an object from one activity to another activity we can use Java serializable in Android. All subtypes of a serializable class are serializable themselves. The interface has no fields and methods that can only serve to identify the semantics of being serializable.

Although it is considered as a slower way of transferring data between activities as compare to Parcelable.

Parcelable the process is faster than Serializable but using serializable we have to write less boilerplate code. One of the reasons for this is that we are being explicit about the serialization process instead of using reflection. It also stands to reason that the code has been heavily optimized for this purpose. In the following example, you can see how easily we can pass our class objects between the Activities using Serializable Interface.

Implement Serializable in your Model Class

class UserModel() : Serializable {
    var id: String? = null
    var name: String? = null // Add other propeties & methods
}

Pass Object From One Activity to Another in Intent

val user = UserModel()
val intent = Intent(this, Activity2::class.java)
intent.putExtra("user", user)
startActivity(intent)

Receive Object in Second Activity From Intent

Add the following code in onCreate() method.

val intent = getIntent()
val user: UserModel? = intent.getSerializableExtra("user") as UserModel?

That’s it. You can use this user object in your second activity. In this article, you have learned how to Pass Object from One Activity to Another using Serializable in Android using Kotlin.

For other helping, code snippets have a look at our Articles List.

Feel free to ask your questions or give suggestions in the comments section below. Thanks

Please share this post:
Posts created 41

Ask a Question

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Related Posts

Begin typing your search term above and press enter to search. Press ESC to cancel.

%d bloggers like this: