1

I am trying to send categories data (ArrayList) from a fragment to another fragment using navigation argument like this.

fun setUpArgumentForSearchDestination(categories: ArrayList<Category>) {

    val searchDestination = fragmentView.findNavController().graph.findNode(R.id.destination_search)
        searchDestination?.addArgument(
            "allCategories", NavArgument.Builder()
            .setType(NavType.ParcelableArrayType(Category::class.java))
            .setDefaultValue(categories)
            .build())
        }

and in the search fragment, I receive the data from argument like this:

       arguments?.let {
            // I get error in the code below:
            val categories = it.getParcelableArrayList<Category>("allCategories")

        }

and I get error message:

java.util.ArrayList cannot be cast to android.os.Parcelable[]

I have tried to find the answer even though I am not sure the cause of this problem, it seems that I have to custom my Category class like in this thread: Read & writing arrays of Parcelable objects

but I am a beginner, and not really understand with that answer from that thread. I have tried to implement parcelable, but it still doesn't work. here is my Category class

class Category() : Parcelable {

    var id : Int = 0
    var name : String = ""
    var parentID : Int = 0
    var imageURL : String = ""

    constructor(parcel: Parcel) : this() {
        id = parcel.readInt()
        name = parcel.readString()
        parentID = parcel.readInt()
        imageURL = parcel.readString()
    }


    override fun writeToParcel(parcel: Parcel, flags: Int) {

        parcel.apply {
            writeInt(id)
            writeString(name)
            writeInt(parentID)
            writeString(imageURL)
        }

    }

    override fun describeContents(): Int {
        return 0
    }



    companion object CREATOR : Parcelable.Creator<Category> {

        override fun createFromParcel(parcel: Parcel): Category {
            return Category(parcel)
        }

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

}
Alexa289
  • 8,089
  • 10
  • 74
  • 178

1 Answers1

6

A ParcelableArrayType only supports arrays of Parcelable objects, not lists. Therefore you must convert your ArrayList into an array using toTypedArray():

val searchDestination = fragmentView.findNavController().graph.findNode(R.id.destination_search)
    searchDestination?.addArgument(
        "allCategories", NavArgument.Builder()
        .setType(NavType.ParcelableArrayType(Category::class.java))
        .setDefaultValue(categories.toTypedArray())
        .build())
    }

You'd retrieve your array of Parcelables using Safe Args or code such as:

arguments?.let {
    val categories = it.getParcelableArray("allCategories") as Array<Category>
}

Navigation does not support ArrayLists of Parcelables.

ianhanniballake
  • 191,609
  • 30
  • 470
  • 443