I've tried using Json, kotlin serialization, Parcelable, but nothing works.
The code of my class looks like this:
data class Item(
var name: String,
var children: MutableList<Item> = mutableListOf(),
var parent: Item? = null
)
The bottom line is that it is tedious for me to save an instance of a class with its parents and children. How can I do this?
I tried inheriting from Parcelable
data class Item(
var name: String,
var children: MutableList<Item> = mutableListOf(),
var parent: Item? = null
) : Parcelable {
constructor(parcel: Parcel) : this(
parcel.readString()!!,
mutableListOf<Item>().apply {
parcel.readTypedList(this, Item.CREATOR)
},
parcel.readParcelable(Item::class.java.classLoader)
)
override fun writeToParcel(parcel: Parcel, flags: Int) {
parcel.writeString(name)
parcel.writeTypedList(children)
parcel.writeParcelable(parent, flags)
}
override fun describeContents(): Int {
return 0
}
companion object CREATOR : Parcelable.Creator<Item> {
override fun createFromParcel(parcel: Parcel): Item{
return Item(parcel)
}
override fun newArray(size: Int): Array<Item?> {
return arrayOfNulls(size)
}
}
}