หลายๆคนคงจะเคยส่งข้อมูลเป็น Object ระหว่าง Activity หรือ fragment ด้วยการ put เป็น Parcelable โดยที่คลาสModel ของ Object ที่จะส่งนั้นจะต้อง implement parcelable ด้วย และต้องเขียน writeToParcel ตัวแปรใน Model ทีละตัว ค่อนข้างเสียเวลาใช่ไหมหล่ะ Android studio ที่กลายร่างมาจาก intellij นั้นมี plugin ดีๆที่ช่วย generate parcel เลยไม่ต้องไปเขียนเอง จึงหยิบเอา Android Parcelable code generator มาเป็นบทความเรื่องนี้ครับ
สำหรับใครที่ยังไม่เคยใช้ Parcelable ลองไปอ่านบทความจาก blog martroutine ดูก่อนครับ
Android Parcelable code generator
เริ่มจากการ Install Plugin กันก่อน
Android Studio -> File -> Settings -> Plugins -> Browse repositores
แล้วพิมพ์ Android Parcelable code generatorในช่อง Search
เมื่อเห็น plugin ให้เลือกแล้วกด Install plugin
หลังจากติดตั้งแล้วก็ restart Android Studio

เมื่อเป็น Android studio มาอีกรอบ Plugin ก็พร้อมใช้งานแล้ว
วิธีการใช้งาน
สร้างคลาสและตัวแปรที่ต้องการเก็บข้อมูล
1 2 3 4 5 6 7 8 9 10 11 12 |
public class User { private String _id; private String name; private String email; private String gender; private int age; private double latitude; private double longitude; private boolean active; } |
จากนั้นเลือก code->generate
หรือ [Alt + Insert]
แล้วเลือก Parcelable
เจ้า Plugin ตัวนี้ก็จะทำการ genarate code โดยการ implement Parcelable , writeToParcel และ filed CREATOR มาให้แบบนี้
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 |
public class User implements Parcelable { private String _id; private String name; private String email; private String gender; private int age; private double latitude; private double longitude; private boolean active; @Override public int describeContents() { return 0; } @Override public void writeToParcel(Parcel dest, int flags) { dest.writeString(this._id); dest.writeString(this.name); dest.writeString(this.email); dest.writeString(this.gender); dest.writeInt(this.age); dest.writeDouble(this.latitude); dest.writeDouble(this.longitude); dest.writeByte(active ? (byte) 1 : (byte) 0); } public User() { } protected User(Parcel in) { this._id = in.readString(); this.name = in.readString(); this.email = in.readString(); this.gender = in.readString(); this.age = in.readInt(); this.latitude = in.readDouble(); this.longitude = in.readDouble(); this.active = in.readByte() != 0; } public static final Parcelable.Creator<User> CREATOR = new Parcelable.Creator<User>() { public User createFromParcel(Parcel source) { return new User(source); } public User[] newArray(int size) { return new User[size]; } }; } |
ทีนี้เราก็จะได้คลาสที่พร้อมนำไปใช้ put parcelable แล้วครับ
มีอีกบทความที่น่าสนใจจาก blog artit-k.com เกี่ยวกับ Parceler Library ก็เป็นอีกวิธีที่น่าสนใจเช่นกันครับ
Thx.