Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get Serializable ArrayList on Intent fragment

On my fragment I want to get ArrayList<Animal>. I have created a newInstance function.

  companion object {
    private val ARG_TITLE = "ARG_TITLE"
    private val ARG_ANIMALS = "ARG_ANIMALS"

    fun newInstance(title: String,animals: ArrayList<Animal>): ExampleFragment{
        val fragment = ExampleFragment()
        val args = Bundle()
        args.putString(ARG_TITLE, title)
        args.putSerializable(ARG_ANIMALS, animals)
        fragment.arguments = args
        return fragment
    }
}

And on my onCreate() I have this.

 private var title: String = ""
lateinit private var animals:ArrayList<Animal>

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    if (arguments != null) {
        title = arguments.getString(ARG_TITLE)
        animals = arguments.getSerializable(ARG_ANIMALS)
    }
}

But

Required: ArrayList found Serialized!

Can't cast to ArrayList neither.

like image 275
Aris Guimerá Avatar asked Mar 04 '18 11:03

Aris Guimerá


1 Answers

As mentioned in a comment, cast it:

NOTE: casting to Serializable isn't necessary if it's an ArrayList (this means ArrayList - List and MutableList are affected differently). List and MutableList has to be cast to Serializable (otherwise it shows an "incompatible types" error)

args.putSerializable(ARG_ANIMALS, animals as Serializable) //This is to cast it to the appropriate form in order for it to be serialized properly

and mirror it on output:

Casting here is necessary no matter what. Otherwise you'll just get a Serializable and not the class which you have serialized.

animals = arguments.getSerializable(ARG_ANIMALS) as ArrayList<Animal>

Type has to be specified in the diamond, otherwise you get an error as a result of animals: ArrayList<Animal> not matching ArrayList<*>

You may want to look into using List instead of ArrayList though, to generalize which types you accept (include MutableList for an instance).

And this only works if Animal implements Serializable. Otherwise it'll crash when you put/get the list from the bundle. Lists are only serializable if the class in them are too.

like image 131
Zoe stands with Ukraine Avatar answered Sep 27 '22 23:09

Zoe stands with Ukraine