首页 > 解决方案 > 使用导航参数传递数据时,如何解决错误 ArrayList cannot be cast to android.os.Parcelable[] in Kotlin?

问题描述

我正在尝试使用这样的导航参数将类别数据(ArrayList)从一个片段发送到另一个片段。

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())
        }

在搜索片段中,我从这样的参数接收数据:

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

        }

我收到错误消息:

java.util.ArrayList 不能转换为 android.os.Parcelable[]

即使我不确定这个问题的原因,我也试图找到答案,看来我必须Category像在这个线程中那样自定义我的类:Read & writing arrays of Parcelable objects

但我是初学者,并不太了解该线程的答案。我已经尝试实现parcelable,但它仍然不起作用。这是我的Category

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)
        }
    }

}

标签: androidkotlinandroid-navigationandroid-jetpackandroid-architecture-navigation

解决方案


AParcelableArrayType只支持对象数组Parcelable不支持列表。因此,您必须ArrayList使用以下方法将您的转换为数组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())
    }

您将使用Safe Args或代码检索 Parcelables 数组,例如:

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

导航不支持 Parcelables 的 ArrayLists。


推荐阅读