简体   繁体   中英

How to use parcelable with setters and getters?

I'm using the parcelable implemenation because it's easier to pass an ArrayList with putParcelableArrayListExtra , but what is the purpose of protected Song(Parcel in) and public void writeToParcel(Parcel dest, int flags)

My parcelable class

public class Song implements Parcelable {

    private long id = 0;
    private String data = "";
    private String title = "";
    private String artist = "";

    public Song(){
    }

    protected Song(Parcel in) {
          id = in.readLong();
          data = in.readString();
          title = in.readString();
          artist = in.readString();
    }

    @Override
    public void writeToParcel(Parcel dest, int flags) {
        dest.writeLong(id);
        dest.writeString(data);
        dest.writeString(title);
        dest.writeString(artist);
    }

    public void setId(long songId){ this.id = songId; }
    public long getId(){
        return id;
    }
    public void setData(String data) { this.data = data; }
    public String getData(){return data;}

    //Optional meta data

    public void setTitle(String title){ this.title = title; }
    public String getTitle() { return title; }

    public void setArtist(String artist){
        this.artist = artist;
    }
    public String getArtist() {
        return artist;
    }

For what is this used, do i still need to add this if i'm not passing any parameters to my Song() constructor or can i just leave it empty?

protected Song(Parcel in) {
            id = in.readLong();
            data = in.readString();
            title = in.readString();
            artist = in.readString();
        }

 @Override
        public void writeToParcel(Parcel dest, int flags) {
            dest.writeLong(id);
            dest.writeString(data);
            dest.writeString(title);
            dest.writeString(artist);
        }

We need this method because it overrides method and with the help getter and setter will work automatically if you don't remove this and manually make setter & getter

@Override
public void writeToParcel(Parcel dest, int flags) {
     dest.writeLong(id);
     dest.writeString(data);
     dest.writeString(title);
     dest.writeString(artist);
}

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