Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bundle size in bytes

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.

like image 954
Ayush Khare Avatar asked Jul 26 '17 05:07

Ayush Khare


People also ask

What is bundle key?

Android Bundles are generally used for passing data from one activity to another. Basically here concept of key-value pair is used where the data that one wants to pass is the value of the map, which can be later retrieved by using the key.

What is a bundle in Java?

a bundle is a JAR file that: Contains […] resources. Contains a manifest file describing the contents of the JAR file and providing information about the bundle.

What does a bundle object contain?

Bundles are generally used for passing data between various Android activities. It depends on you what type of values you want to pass, but bundles can hold all types of values and pass them to the new activity.

What is the best definition for Bundle Android?

Bundle is used to pass data between Activities. You can create a bundle, pass it to Intent that starts the activity which then can be used from the destination activity.


3 Answers

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
}
like image 81
Martynas Jurkus Avatar answered Oct 13 '22 03:10

Martynas Jurkus


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;
}
like image 40
Volodymyr Kononenko Avatar answered Oct 13 '22 03:10

Volodymyr Kononenko


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.

like image 2
M.Ed Avatar answered Oct 13 '22 05:10

M.Ed