Prajeet Shrestha
Prajeet Shrestha

Reputation: 8108

How to solve Kotlin typecast issue?

I want to pass array of custom object through intent.

    val valuesToBeSent =  listOf(
            RSSSource("title", "someurl"),
            RSSSource("title2", "someurl")
    ).toTypedArray()

    val i = Intent(this, SecondActivity::class.java)
    i.putExtra("SOURCES", valuesToBeSent)
    startActivity(i)

    //ONSECOND ACTIVITY

    val rssSources = intent?.extras?.getSerializable("SOURCES") as? Array<RSSSource>

I could pass the values like this from one activity to another activity. But it gives following warning in android studio, when I try to typecast value. I converted list into typed array since, list couldn't be pass through intent as extras.

enter image description here

Also, even if I cast it ignoring warning I could access values of the array in second activity in devices supporting SDK > 21 but in devices supporting SDK 19 it crashes the app.

What is the proper way to send the array of custom objects through intent?

Upvotes: 0

Views: 788

Answers (1)

Volodymyr R.tmnko
Volodymyr R.tmnko

Reputation: 485

You just need to put in Intent right data structure. Something that could be serialized. Use ArrayList, why not ? It serializes correctly and works like a sharm. If I could write code for test collection serialization via intent I would write something like this.

 fun testIntent() {
  val KEY = "key"
  val list = arrayListOf("one", "another")
  val intent = Intent().putExtra(KEY, list)
  val bundle = intent.getSerializableExtra(KEY) as? java.util.ArrayList<String> ?: emptyList<String>()

  assert(bundle[0] == "one")
}

Upvotes: 2

Related Questions