Search code examples
javaandroidparcelableparcel

How to make class with multiple Integers and Strings Parcelable?


I have following Class and i want to make it Parcelable Problem is that when i read isHidden and Counter variable from int[] arraySongIntegers by method in.createIntArray() , i am getting an empty array of size 0 and BTW all the String variables are being read correctly . Please tell me how do i write all variables to Parcel and read it back properly.

public class Song implements Parcelable{
    public static long firstSongId;
    private long id;
    private String title ,mimeType, artist , dateAdded ,album;
    private int isHidden ,counter;    // 0 is false , 1 is true

 public Song(Parcel in){
    readFromParcel(in);
 }

@Override
public void writeToParcel(Parcel dest, int flags) {
    int[] arraySongIntegers = new int[2];
    arraySongIntegers[0] = isHidden;
    arraySongIntegers[1] = counter;
    dest.writeIntArray(arraySongIntegers);


    dest.writeLong(id);

    List<String> l  = new ArrayList<>();
    l.add(title);
    l.add(artist);
    l.add(album);
    l.add(dateAdded);
    dest.writeStringList(l);

}


public void readFromParcel(Parcel in){

    id = in.readLong();

    int[] arraySongIntegers = in.createIntArray();
    isHidden = arraySongIntegers[0];
    counter = arraySongIntegers[1];

    ArrayList<String> list = in.createStringArrayList();
    title = list.get(0);
    artist = list.get(1);
    album = list.get(2);
    dateAdded = list.get(3);
}

public static final Parcelable.Creator CREATOR =
        new Parcelable.Creator() {
            public  Song createFromParcel(Parcel in) {
                return new Song(in);
            }

            public  Song[] newArray(int size) {
                return new Song[size];
            }
        };

}

Thanks in advance.


Solution

  • In addition to my comment (there's no reason to make it an array)- you need to read everything in the order you write it. By reading the id first everything gets screwed up.