Reputation: 1495
I need to pass this:
private lateinit var memes: MutableList<Memes>
which has this model:
class Memes (
@SerializedName("id") var id: Long,
@SerializedName("title") var title: String
)
from activity a to b.
I've altready seen couple "solutions" and none of them works!
This is the last that I've tried:
val extras = Bundle()
val memesArrayList = ArrayList(memes)
val i = Intent(context, GalleryShow::class.java)
i.putExtras(extras)
i.putStringArrayListExtra("list", memesArrayList)
(context as Activity).startActivityForResult(i, 777)
However, I get Type mismatch: inferred type is ArrayList<Memes!> but ArrayList<String!>? was expected
on memesArrayList
.
EDIT:
This is my latest attempt now:
In activity A inside recyclerview item:
val extras = Bundle()
extras.putString("gal", "animals")
extras.putString("query", "")
val i = Intent(context, GalleryShow::class.java)
i.putExtra("list", memes.toTypedArray())
i.putExtras(extras)
(context as Activity).startActivityForResult(i, 777)
and this is inside activity B:
private lateinit var memes: MutableList<Memes>
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_gallery_show)
memes = (this?.intent?.extras?.get("list") as? Array<Memes>)?.asList()!!.toMutableList()
}
Upvotes: 0
Views: 633
Reputation: 93629
You can use simply intent.putExtra
instead of worrying about which variant like put_____Extra
to use.
When extracting the value, you can use intent.extras
to get the Bundle and then you can use get()
on the Bundle and cast to the appropriate type. This is easier than trying to figure out which intent.get____Extra
function to use to extract it, since you will have to cast it anyway.
The below code works whether your data class is Serializeable or Parcelable. You don't need to use arrays, because ArrayLists themselves are Serializeable, but you do need to convert from MutableList to ArrayList.
// Packing and sending the data:
val i = Intent(context, GalleryShow::class.java)
i.putExtra("list", ArrayList(memes)) // where memes is your MutableList<Meme> property
startActivityForResult(i, 777)
// Unpacking the data in the other activity:
memes = intent.extras?.get("list") as MutableList<Meme>
Upvotes: 1