0

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)
        }
    }
}

Murlodin
  • 1
  • 1
  • 2
    You shouldn't use `Parcelable` to write to disk (e.g., SharedPreferences). The format isn't stable and can (and does) change between Android versions. `Serializable` would work, though. – Ryan M Mar 28 '23 at 13:11
  • If you are saving objects, just go with Proto Datastore https://developer.android.com/topic/libraries/architecture/datastore – coroutineDispatcher Mar 28 '23 at 13:57

0 Answers0