mutableListOf to Bundle (Kotlin)

1.1k Views Asked by At

I have a mutableLIst:

var books = mutableListOf<Book>()

model "Book" is:

data class Book(val title: String, val id: Int)

My code is:

      button2.setOnClickListener{
        val delFragment = DelFragment()
        val booksforDel = Bundle()
        booksforDel.putStringArrayList("books", books as ArrayList<String>)
        delFragment.setArguments(booksforDel)

        val manager = supportFragmentManager
        delFragment.show(manager,"Delete Book")
    }

in Fragment I try to get data:

val booksForDelete = getArguments()?.getStringArrayList("books")!!

And get Error:

java.lang.ArrayStoreException: source[0] of type com.example.http_example.model.Book cannot be stored in destination array of type java.lang.String[]

How send a data from mutableList "books" to Bundle in DialogFragment?

1

There are 1 best solutions below

4
On

You can implement Parcelable interface:

data class Book(val title: String, val id: Int) : Parcelable {
    constructor(source: Parcel) : this(
            source.readString()!!,
            source.readInt()
    )

    override fun describeContents() = 0

    override fun writeToParcel(dest: Parcel, flags: Int) = with(dest) {
        writeString(title)
        writeInt(id)
    }

    companion object {
        @JvmField
        val CREATOR: Parcelable.Creator<Book> = object : Parcelable.Creator<Book> {
            override fun createFromParcel(source: Parcel): Book = Book(source)
            override fun newArray(size: Int): Array<Book?> = arrayOfNulls(size)
        }
    }
}

And use it like the following:

var books = mutableListOf<Book>()
val booksforDel = Bundle()
booksforDel.putParcelableArray("books", books.toTypedArray())

Ann to retrieve books in a Fragment:

val booksForDelete = arguments?.getParcelableArray("books")