如何避免得到“android.os.TransactionTooLargeException”

问题描述 投票:0回答:1

在android应用程序中,有些情况需要传递一些数据,交叉活动/片段,传递给服务等。它一直在使用parcelable并放入intent / bundle。它可以正常工作,除非在某个时间超过可分配的一个meg限制时崩溃。

android.os.TransactionTooLargeException: data parcel size 526576 bytes

试着看看它是否可以将parcelable对象的内容放入lruCache中,所以基本上用自己的lruCache实现替换parcelable的save / loading。

这种方法有问题吗?或者解决问题的任何建议/替代方案?

@ApiSerializable
class  DataItem (
        @SerializedName("uuid")
        var uuid: String = "",

        @SerializedName("image")
        val mainImage: Image?,  //another parcelable type

        @SerializedName("entities")
        var entities: List<EntityInfo>?,


        //......
        // a lot of data
        //......
        //......

) : BaseDataItem(), IData {

    override fun uuid(): String {
        return uuid
    }

    //......


    constructor(parcel: Parcel) : this(
            parcel.readString(), //uuid

            //...
            //...

            parcel.readParcelable(Image::class.java.classLoader),
            mutableListOf<EntityInfo>().apply {
                parcel.readTypedList(this, EntityInfo.CREATOR)
            }) {

    }


    override fun writeToParcel(parcel: Parcel, flags: Int) {
        parcel.writeString(uuid ?: "")

        //......
        //......

        parcel.writeParcelable(mainImage, flags)
        parcel.writeTypedList(entities)

    }

    override fun describeContents(): Int {
        return 0
    }

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

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

方法是使用lruCache本身替换parcel部分的保存/加载:

    // having the cache somewhere
    val dataCache =  LruCache<String, IData>(200)

并且只有一个字符串成员使用Parcel保存/加载:

    fun init (copyData: DataItem) {
        // do sopy over from the copyData
    }

    constructor(parcel: Parcel) : this() {
        uuid = parcel.readString(), //uuid

        val _thisCopy = dataCache.get(uuid)

        init(_thisCopy)

    }

    override fun writeToParcel(parcel: Parcel, flags: Int) {
        parcel.writeString(uuid ?: "")

        dataCache.put(uuid, this)
    }
android parcelable android-lru-cache
1个回答
0
投票

您应该避免将包含大量数据的整个Object传递给Next活动。因此,您的Object可能有很多数据。所以有时系统无法一次处理大量数据。尝试使用“首选项”来存储对象数据,并在其他活动中检索相同的数据。

请给我答案:Exception when starting activity android.os.TransactionTooLargeException: data parcel size

© www.soinside.com 2019 - 2024. All rights reserved.