Solution 1 :
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")
Problem :
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?
Comments
Comment posted by Дмитрий
it’s work. how to organize setSingleChoiceItems for bookForDelete? I make a code: .setSingleChoiceItems(booksForDelete?.map(Book::title)?.toTypedArray(),checkedItem){ dialog, which -> Toast.makeText(activity,”Choosen book: ${booksForDelete?.map { Book::title}?.get(which)}”,Toast.LENGTH_SHORT).show() } IDE marked “map” in the first line
Comment posted by Sergio
Please create another question on Stackoverflow and include all information there, give me a link here, and I’ll try to help.
Comment posted by Дмитрий
ok. i try. я вам очень признателен за помощь. потому как только осваиваю Kotlin.
Comment posted by momvart
instead of implementing