Type mismatch: inferred type is Array<Profile> but Array<(out) Parcelable!>? was expected Navigation graph

2.3k Views Asked by At

I am trying to pass an ArrayList<Profile> in a bundle from one fragment to another using the Navigation Graph, but I am getting this error Type mismatch: inferred type is Array<Profile> but Array<(out) Parcelable!>? was expected I have already passed on the navigation the type of argument that I want to pass. What am I missing? Here my code

Code that passes the argument

 emptyHomeViewModel.playerByIDLiveData.observe(viewLifecycleOwner) { profile ->
                    if (profile != null) {
                        profilesList.add(profile)
                        bundle = Bundle().apply {
                            putSerializable("user", profilesList)
                        }
                        findNavController().navigate(
                            R.id.action_emptyHomeFragment_to_selectUserFragment,
                            bundle
                        )

Navigation XML for the fragment that will receive

 <fragment
        android:id="@+id/selectUserFragment"
        android:name="com.example.dota2statistics.SelectUserFragment"
        android:label="fragment_select_user"
        tools:layout="@layout/fragment_select_user" >
        <argument
            android:name="user"
            app:argType="com.example.dota2statistics.data.models.byID.Profile[]" />
    </fragment>

Code of the fragment that receives the ArrayList

class SelectUserFragment : Fragment(R.layout.fragment_select_user) {

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        val args : SelectUserFragmentArgs by navArgs()
        val profilesList = args.user

        Log.i("Profiles", "onViewCreated: ${profilesList[0].personaname} ================")
    }
1

There are 1 best solutions below

3
On

add this plugin

plugins {
     id("kotlin-parcelize")
}

then make your class parcelable for example

import kotlinx.parcelize.Parcelize

@Parcelize
class User(val firstName: String, val lastName: String, val age: Int): Parcelable

Safe args only allows passing Array so before adding bundle we have to convert ArrayList to Array

bundle.putParcelableArray("user", profilesList.toTypedArray())

Then when getting the argument we can convert it back to ArrayList

val list: ArrayList<Profile> = ArrayList(args.user.toList())