It means to put an object into a state that can be stored or transferred. Serialized objects can be transferred over the network or stored locally. Serialization is very simple, they just need to inherit Serializable or Parcelable
It is recommended to use Parcelable because it saves performance
Serializable
- The object is serialized, which is performance-expensive
package com.example.serializabledemo.model
import java.io.Serializable
class Person : Serializable {
var name = ""
var age = 0
}
Copy the code
- use
package com.example.serializabledemo
import android.os.Bundle
import android.util.Log
import androidx.appcompat.app.AppCompatActivity
import com.example.serializabledemo.model.Person3
class SecondActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?). {
super.onCreate(savedInstanceState)
val person = intent.getSerializableExtra("person_data") as Person
Log.d("Person is ", person.age.toString())
}
}
Copy the code
Parcelable
- The idea is to break up the object, each part of which is a type supported by the Intent, so performance is better and more recommended
- The first way:
package com.example.serializabledemo.model
import android.os.Parcel
import android.os.Parcelable
class Person2 : Parcelable {
var name: String = ""
var age: Int = 0
override fun writeToParcel(dest: Parcel, flags: Int) {
dest.writeString(name)
dest.writeInt(age)
}
override fun describeContents(a): Int {
return 0
}
companion object CREATOR : Parcelable.Creator<Person> {
override fun createFromParcel(source: Parcel): Person {
val person = Person()
person.name = source.readString() ?: "" / / read the name
person.age = source.readInt() / / read the age
return person
}
override fun newArray(size: Int): Array<Person? > {return arrayOfNulls(size)
}
}
}
Copy the code
- Kotlin’s simpler way of writing it
package com.example.serializabledemo.model
import android.os.Parcelable
import kotlinx.android.parcel.Parcelize
@Parcelize
class Person3(var name: String, var age: Int) : Parcelable
Copy the code
- use
package com.example.serializabledemo
import android.os.Bundle
import android.util.Log
import androidx.appcompat.app.AppCompatActivity
import com.example.serializabledemo.model.Person3
class SecondActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?). {
super.onCreate(savedInstanceState)
val person = intent.getParcelableExtra("person_data") as Person3
Log.d("Person is ", person.age.toString())
}
}
Copy the code