0

I'm studying the Interface Parcelable and I'm facing some problems trying to fully understand how it works. On the internet I didn't find answers to some of my questions:

I show you my Class:

public class Media implements IModel, Parcelable{

    private Uri uri;
    private long _ID;
    private boolean isOnDb = false;
    private boolean isSelected = false;

    /*Getter and setter methods
    ........
    */    


    /***********************************   Parcelable **********************************/
    public static final Parcelable.Creator CREATOR = new Parcelable.Creator<Media>(){
        @Override
        public Media createFromParcel(Parcel parcel) {
            return new Media(parcel);
        }

        @Override
        public Media[] newArray(int i) {
            return new Media[i];
        }
    };

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

    @Override
    public void writeToParcel(Parcel parcel, int i) {
        parcel.writeParcelable(uri, 1);
        parcel.writeLong(_ID);
        parcel.writeByte((byte) (isOnDb ? 1 : 0));
        parcel.writeByte((byte) (isSelected ? 1 : 0));
    }

    private Media (Parcel parcel){
        uri = parcel.readParcelable(Uri.class.getClassLoader());
        _ID = parcel.readLong();
        isOnDb = parcel.readByte() != 0;
        isSelected = parcel.readByte() != 0;
    }
}

Question 1 As you can see, I have a constructor with just 2 field Media(Uri uri, long _ID). Is it a problem if the method writeToParcel() and the constructor private Media (Parcel parcel) menage 4 fields inside their body? I mean...the fields managed by private Media (Parcel parcel) and writeToParcel() should reflect the number of fields passed to the "other" contructor?

Question 2 How should I manage a Uri field? Is it correct the way I did it? P.S.: I don't understand why I can't write parcel.writeSerializable(Uri); I get a compile error even though Uri class implements Serializable.

Thank you in advance

MDP
  • 4,177
  • 21
  • 63
  • 119

1 Answers1

1

Is it a problem if the method writeToParcel() and the constructor private Media (Parcel parcel) menage 4 fields inside their body?

That should be fine.

How should I manage a Uri field? Is it correct the way I did it?

What you have should be fine. Personally, I would convert it to and from a string, just because I hate messing with classloaders.

I get a compile error even though Uri class implements Serializable.

Uri does not implement Serializable. It implements Parcelable. See the JavaDocs.

CommonsWare
  • 986,068
  • 189
  • 2,389
  • 2,491