简体   繁体   中英

Android multiple parcelable constructors

I have a object class that I need to have two constructors for it. Ex.

//first constructor
public MyObject(int contract_id, String id, String title, String body) {
        super();
        this.contract_id = contract_id;
        this.id = id;
        this.title = title;
        this.body = body;
    }

//second constructor with extra parameters
public MyObject(int contract_id, String id, String title, String body,String time,String nickName) {
        super();
        this.contract_id = contract_id;
        this.id = id;
        this.title = title;
        this.body = body;
        this.time=time;
        this.nickName=nickName;
    }

The thing is that I know how to do parcelable for one objects that have one constructor, but what about this case? How should I recognize what constructor is called so I can create the right parcels?

You can use Parcel.dataSize() which

Returns the total amount of data contained in the parcel.

or Parcel.dataAvail()

Returns the amount of data remaining to be read from the parcel. That is, dataSize()-dataPosition().

Fe define a constructor which takes a Parcel as parameter and check how much data is remaining:

MyObject(Parcel in) {

   this.contract_id = in.readInt();
   this.id = in.readString();
   this.title = in.readString();
   this.body = in.readString(); // till here both constructors have same data

   if (in.dataAvail() > 0) { // check for the extra data

       this.time = in.readString();
       this.nickName = in.readString();

   }
}

Use this constructor in your CREATOR like this:

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM