Passing List of Objects to Fragment

kokilayaa picture kokilayaa · Dec 26, 2017 · Viewed 12.9k times · Source
class CholesterolPagingFragment: Fragment() {

    companion object {
        fun newInstance(): CholesterolPagingFragment {
            val args = Bundle()
            val fragment = CholesterolPagingFragment()
            fragment.arguments = args
            return fragment
        }
    }

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
        val view = inflater.inflate(R.layout.fragment_paging_cholesterol, container, false)

        return view
    }

}

I have wrote the above code in Kotlin to initialize a fragment. Though I can't figure out a way to pass a list of objects(eg: List<Human>) to this fragment. I have tried with the Bundle() but couldn't find a proper way.

Answer

Yamini Balakrishnan picture Yamini Balakrishnan · Dec 26, 2017

You can pass List<Human> as Parcelable ArrayList to the Bundle as follows:

 companion object {
    fun newInstance(myList : ArrayList<Human>): MyFragment {
        val args = Bundle()
        args.putParcelableArrayList("list",myList);
        val fragment = MyFragment()
        fragment.arguments = args
        return fragment
    }
}

To retrieve data:

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)

    val args = arguments
    var myList : ArrayList<Human> = args.getParcelableArrayList<Human>("list")
}

Do Parcelable implementation in Human Data Class :

data class Human(val name: String, val phone: String) : Parcelable {
    constructor(parcel: Parcel) : this(
            parcel.readString(),
            parcel.readString()) {
    }

    override fun writeToParcel(dest: Parcel?, flags: Int) {
        TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
    }

    override fun describeContents(): Int {
        TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
    }

    companion object CREATOR : Parcelable.Creator<Human> {
        override fun createFromParcel(parcel: Parcel): Human {
            return Human(parcel)
        }

        override fun newArray(size: Int): Array<Human?> {
            return arrayOfNulls(size)
        }
    }
}