Passing Parceleable Object to Fragment Type Mismat

2019-08-31 09:30发布

问题:

I'm new to kotlin and trying to pass an object from my adapter to a fragment. But I am getting a type mismatch in the companion object for booklist. It says Required: Parceleable Found: List<ResourcesList>?

I've also tried using putParcelableArrayList and putParcelableArray and Serializable but also with the same type mismatch.

My data model looks like this:

@Parcelize
class ResourcesList (val id: Int,
                     val name: String,
                     val content: Contents,
                     val tags: List<Tags>) : Parcelable

@Parcelize
class Contents       (val id: Int,
                     val producers: List<Producers>,
                     val categories: List<Categories>,
                     val isAvailable: Boolean): Parcelable
@Parcelize
class Producers     (val name: String,
                     val role: String): Parcelable
@Parcelize
class Categories    (val id: Int,
                     val name: String): Parcelable

Fragment

class SeeAllFragment: Fragment() {

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


        val bookslist = arguments.getParceleable("bookslist")

        return view
    }

    companion object {

        fun newInstance(bookslist: List<ResourcesList>?): SeeAllFragment {

            val args = Bundle()
            args.putParcelable("bookslist", bookslist)
            val fragment = SeeAllFragment()
            fragment.arguments = args
            return fragment
        }
    }
}

回答1:

for putting list in bundle :

args.putParcelableArrayList("bookslist", bookslist as ArrayList<out Parcelable>?)

for getting list :

val bookslist = arguments.getParcelableArrayList<ResourcesList>("bookslist")


回答2:

In my coding I using Gson.

companion object {
    const val BOOK_LIST = "bookslist"
    fun getFragment(bookslist: List<ResourcesList>): SeeAllFragment {
        return SeeAllFragment().apply { arguments = Bundle().apply {
            putString(BOOK_LIST, Gson().toJson(bookslist))
        } }
    }
}

Then get data like this.

val bookslist = Gson().fromJson(arguments?.getString(BOOK_LIST), object : TypeToken<List<ResourcesList>>() {}.type)