Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass a mutableList from activity A to activity B in Kotlin.

I'm trying to pass data from activity A to activity B through intent in Kotlin.

The problem is I have a videos: MutableList<Video> and the intent.putParcelableArrayListExtra("VIDEOS", videos) only accepts ArrayList<out Parcelable> as arguments.

Questions

*. How do I send a mutableList data from activity A to activity B?

*. Or Do I have to convert it to ArrayList<Video> ?

PS: Videoimplements Parcelable

like image 621
Puni Avatar asked Jan 31 '18 11:01

Puni


People also ask

How do you pass data class from one activity to another Kotlin?

To move from one activity to another, we use Intent and to pass the object of Product we use putExtra method of intent that takes 2 parameters, it is like key value pairs, the first parameter is a unique key and the second parameter is Product object that we want to pass to the SecondActivity.

How do you send an ArrayList to another activity?

You can pass an ArrayList<E> the same way, if the E type is Serializable . You would call the putExtra (String name, Serializable value) of Intent to store, and getSerializableExtra (String name) for retrieval.

How do you pass a mutable list in Kotlin?

To create a mutable list in Kotlin, call mutableListOf() function and pass the elements to it.


2 Answers

Converting it to an ArrayList (or storing it as one in the first place?) is the easy solution if you want to stick to passing it through an Intent. There's an ArrayList constructor that takes a collection as its parameter:

intent.putParcelableArrayListExtra("VIDEOS", ArrayList(videos))
like image 119
zsmb13 Avatar answered Sep 22 '22 00:09

zsmb13


For those asking how the Parcelable class is created, this is the solution I came up with in Kotlin

The Parcelable Class:

@Parcelize
data class ExampleModel(
        var stringOne: String,
        var stringTwo: String): Parcelable

Then in Activity A you can create an ArrayList and send it via intent to Activity B

private var exampleMutableList: MutableList<ExampleModel> = arrayListOf()
exampleMutableList.add(ExampleModel("hello", "world"))
intent.putExtra("example", ArrayList(exampleMutableList))

And in Activity B we can receive our ArrayList:

exampleMutableList = intent.getParcelableArrayListExtra<ExampleModel>("example") as ArrayList<ExampleModel>

All the best!

like image 45
Douglas Hosea Avatar answered Sep 21 '22 00:09

Douglas Hosea