1

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)
Chris Hansen
  • 7,813
  • 15
  • 81
  • 165
  • Implement your Book class as Parcelable & use bundle.putParcelableArrayList & in 2nd activity getParcelableArrayList – Gautam Mar 10 '20 at 04:50

1 Answers1

1

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.

IntelliJ Amiya
  • 74,896
  • 15
  • 165
  • 198
  • putParcelableArrayListExtra("list", list[layoutPosition].list) tells me that the second argument is of the wrong type – Chris Hansen Mar 10 '20 at 04:54
  • @LouisaScheinost seems like you should pass `list[layoutPosition]` instead of `list[layoutPosition].list` – IntelliJ Amiya Mar 10 '20 at 05:14
  • I think this is bad solution, so many time i see app crash when list too large. You can create an variable in MainApplication class, it's better or save it in some database. – Hoàng Vũ Anh Mar 10 '20 at 09:09
  • 1
    It is something to consider: TransactionTooLargeException. The limitation is different on different versions of Android, but you can probably consider it to be 1MB as a baseline. But for a large amount of variable data I would tend to reopen it from the DB in the new Activity. Having said that, the answer above is really educational in terms of what is being attempted. – Elletlar Mar 10 '20 at 09:37