10

I am implementing Parcelable in order to transmit some simple data throughout an Intent.
However, There is one method in the Parcelable interface that I don't understand at all : newArray().
It does not have any relevant documentation & is not even called in my code when I parcel/deparcel my object.

Sample Parcelable implementation :

public class MyParcelable implements Parcelable {
 private int mData;

 public int describeContents() {
     return 0;
     }

 public void writeToParcel(Parcel out, int flags) {
     out.writeInt(mData);
     }

 public static final Parcelable.Creator<MyParcelable> CREATOR
         = new Parcelable.Creator<MyParcelable>() {
     public MyParcelable createFromParcel(Parcel in) {
         return new MyParcelable(in);
         }

     public MyParcelable[] newArray(int size) {
         return new MyParcelable[size];
         }
     };

 private MyParcelable(Parcel in) {
     mData = in.readInt();
     }
 }  

So, my question is : what is this method for ? and when is it called ?
Is there any point in doing something else than return new MyParcelable[size]; in that method ?

Flow
  • 23,572
  • 15
  • 99
  • 156
Teovald
  • 4,369
  • 4
  • 26
  • 45

3 Answers3

9

this is a function to be called when you try to deserialize an array of Parcelable objects and for each single object createFromParcel is called.

vipul mittal
  • 17,343
  • 3
  • 41
  • 44
5

It is there to prepare the typed array without all the generics stuff. That's it.
Returning just the standard return new MyParcelable[size]; is fine.

It is normal, that you never call it yourself. However, by calling something like Bundle.getParcelableArray() you end up in this method indirectly.

flx
  • 14,146
  • 11
  • 55
  • 70
0

newArray is responsible to create an array of our type of the appropriate size

Chetan Pawar
  • 404
  • 3
  • 4