Wednesday, August 21, 2013

Implementing Parcelable interface

When looking for a way to implement Parcelable interface, I found a great parcelabler tool by Dallas Gutauckis to generate code quickly.

Suppose we have a class:

 public class DO {  
      private Long id;  
      private String name;  
      private String desc;  
      private Date created;  
 }  

Then copy and paste into the textbox and click Build button, the result will be:

 public class DO {  
      private Long id;  
      private String name;  
      private String desc;  
      private Date created;  
   protected DO(Parcel in) {  
     id = in.readLong();  
     name = in.readString();  
     desc = in.readString();  
     long tmpCreated = in.readLong();  
     created = tmpCreated != -1 ? new Date(tmpCreated) : null;  
   }  
   public int describeContents() {  
     return 0;  
   }  
   public void writeToParcel(Parcel dest, int flags) {  
     dest.writeLong(id);  
     dest.writeString(name);  
     dest.writeString(desc);  
     dest.writeLong(created != null ? created.getTime() : -1L);  
   }  
   public static final Parcelable.Creator<DO> CREATOR = new Parcelable.Creator<DO>() {  
     public DO createFromParcel(Parcel in) {  
       return new DO(in);  
     }  
     public DO[] newArray(int size) {  
       return new DO[size];  
     }  
   };  
 }  

Although the options for removing fields won't work, but the tool is useful. Thank you Dallas.

No comments:

Post a Comment