Reputation: 1562
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.
Upvotes: 0
Views: 1054
Reputation: 102
You can use Bundle to save key/value pairs into the parcel. For this purpose use the Parcel#writeBundle
method. As in this example:
public void writeToParcel(Parcel parcel, int i) {
Bundle data = new Bundle();
data.putInt("id",id);
data.putInt("year",year);
parcel.writeBundle(data);
}
Upvotes: 0
Reputation: 238
Just use this: http://www.parcelabler.com
Paste the class name + variables to the left textarea, click build and it will produce the right code for you.
For example if I have a class called myClass with 2 strings and 1 integer I would put this code to the textures:
public class myClass
{
private String s1;
private String s2;
private int n1;
}
Upvotes: 1
Reputation: 93668
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.
Upvotes: 2