1

I wanted my POJO to implement Parcelable interface :

import android.os.Parcel;
import android.os.Parcelable;

public class Phone implements Parcelable {
    public int id;
    public String phone;

    @Override
    public int describeContents() {
        return 0;
    }

    @Override
    public void writeToParcel(Parcel out, int i) {
        out.writeInt(id);
        out.writeString(phone);
    }
}

I saw some tutorials (1, 2) where more method were implemented:

 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();
 }

Do I need to implement more methods?

If so, why my IDEA doesn't suggest me to implement them when right clicking on Parcelable interface?

Community
  • 1
  • 1
Elad Benda2
  • 13,852
  • 29
  • 82
  • 157

1 Answers1

1

Please take a look at the docs: http://developer.android.com/reference/android/os/Parcelable.html

It clearly states that:

interface Parcelable.Creator Interface that must be implemented and provided as a public CREATOR field that generates instances of your Parcelable class from a Parcel.

MyParcelable() in term is a constructor. It is needed in the example to initialize the interface implementation object's state (mData field), but is not required by the Parcelable contract. That said, you do need a constructor unless you're going to set the 'id' and 'phone' fields via setters (which you'd need to implement in turn) but that would only make sense if those attributes could change during the life of the object. So depends on your needs.

As for IntelliJ, it does not auto-suggest for CREATOR, because it can only auto-suggest unimplemented methods - the fact that you need to supply creator via some specifically named public variable is not common solution (and crappy imo, but hey), but rather a man-made contract, and cannot be foreseen by the IDE.

Regarding the constructor - interfaces do not have constructors, it's your implementation that needs it - the auto-suggest should pop-up as a highlight on the fields (id, phone) stating that they're not initialized.