how to pass an arraylist of books between activities

Louisa Scheinost :

I have an arraylist of type Book. How can I pass the array list to another activity and read from that list in the other activity? Here's what I have so far.

   txtViewAll.setOnClickListener {
                Intent(context, BookActivity::class.java).apply {
                    putExtra("list", list[layoutPosition].list)
                    context.startActivity(this)
                }
            }

// to read

val bookList = intent.getStringArrayListExtra("list") as ArrayList<Book>
            for (book in bookList) {
                list.add(Book(book.id, book.title, book.image, book.subtitle, null, null, 0, 0));
            }

Here's each Book

data class Book(val id: String, val title: String, var image: String, var subtitle: String, var author: String?, var desc: String?, var uploadDate: Long,  var starCount: Long)
IntelliJ Amiya :

You can use putParcelableArrayListExtra & getParcelableArrayListExtra .

Set this way

Intent(context, BookActivity::class.java).apply {
putParcelableArrayListExtra("list", list[layoutPosition].list)
context.startActivity(this)

Get this way

val bookList = this.intent.getParcelableArrayListExtra<Parcelable>("list") as ArrayList<Book>

You should use Parcelable

  • Use @Parcelize annotation on top of your Model / Data class

Example

@Parcelize
data class Book

Parcelable is an Android only interface which is used to serialize
class so its properties can be transferred from one activity to
another.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=174377&siteId=1