0

I have a data model class CategoryModel:

@Serializable
data class CategoryModel (val name: String, val items: ArrayList<String>) : java.io.Serializable {}

And I am trying to use Serialize so I can store the data from this class into a Bundle to be shared with another class:

    private fun displayCategoryItems(cat: CategoryModel) {

        val categoryItemsIntent = Intent(this, CategoryItemsActivity::class.java)
        val data: String = Json.encodeToString(cat)
        categoryItemsIntent.putExtra(categoryObjKey, data)

        startActivityForResult(categoryItemsIntent,mainActivityReqCode)

    }

I've noticed it has started doing wonky things with array brackets, and it looks like when i try to deserialize it, the items ArrayList is being converted to a string. So instead of

"items": "[1, 2]"

I get

"items":["[1, [2]]"]

What am I doing wrong?

Pwneill
  • 15
  • 1
  • 6

1 Answers1

0

Just put the object that implements Serializable in the extras like:

    private fun displayCategoryItems(cat: CategoryModel) {

            val categoryItemsIntent = Intent(this, 
            CategoryItemsActivity::class.java)?.apply{
                   putExtra(categoryObjKey, data)
            }

           startActivityForResult(categoryItemsIntent,mainActivityReqCode)

    }

or pass like this:

    private fun displayCategoryItems(cat: Any) {
            val categoryItemsIntent = Intent(this, 
            CategoryItemsActivity::class.java)?.apply{
                   putExtra(categoryObjKey, cat as CategoryModel)
            }

           startActivityForResult(categoryItemsIntent,mainActivityReqCode)

    }
  • This helped a lot! I tried to implement this solution and it gave me a NullPointerError in the CategoryItemsActivity class - here's a gist of the relevant portion of that code: https://gist.github.com/pwneill/78b36f5af24e92290ac5f6d99e2914ad – Pwneill Jan 27 '21 at 04:07
  • you will want to ask a new question for that issue. – John Lord Jan 27 '21 at 04:29