Bundle size in bytes
Asked Answered
L

3

23

Is there any way to know the bundle size in bytes? My point in asking this is I am saving parcelable object lists in my bundle on onSaveInstanceState.

I need to check if the bundle size is reached it's size limit and prevent any more data to get saved, and to prevent TransactionTooLarge exception to occur.

Laundes answered 26/7, 2017 at 5:29 Comment(2)
have u check this #47633502Hollah
Can you edit the question and explain to us why below answer not works for you?Presumable
B
23

I think easiest way for me is:

fun getBundleSizeInBytes(bundle : Bundle) : Int {
  val parcel = Parcel.obtain()
  parcel.writeValue(bundle)

  val bytes = parcel.marshall()
  parcel.recycle()

  return bytes.size
}
Bricklayer answered 4/8, 2017 at 6:19 Comment(0)
C
15

Parcel class has dataSize() member, so the same result can be achieved without calling marshall():

int getBundleSizeInBytes(Bundle bundle) {
    Parcel parcel = Parcel.obtain();
    int size;

    parcel.writeBundle(bundle);
    size = parcel.dataSize();
    parcel.recycle();

    return size;
}
Colored answered 25/1, 2018 at 16:6 Comment(1)
this is in bytesChickadee
H
3

Here's the same method provided by @Volodymyr Kononenko using Kotlin's extension function for those interested:

fun Bundle.bundleSizeInBytes(): Int {
    val parcel = Parcel.obtain()
    parcel.writeBundle(this)

    val size = parcel.dataSize()
    parcel.recycle()

    return size
}

In case you want the Bundle's size in Kilobytes instead of bytes

fun Bundle.bundleSizeInKilobytes(): Double {
    val parcel = Parcel.obtain()
    parcel.writeBundle(this)

    val size = parcel.dataSize().toDouble()/1000
    parcel.recycle()

    return size
}

BTW I wouldn't use writeValue() instead of writeBundle() as writeValue() adds extra 4 bytes to the size.

Hunchback answered 17/1, 2022 at 2:32 Comment(1)
Please add toDoubleOrNull() usage. NullPointer friendly.Janeejaneen

© 2022 - 2024 — McMap. All rights reserved.