Reputation: 2965
I have created a Parcelable Object called Task shown below
public final class Task implements Parcelable {
// Lots of code, including parceling a single task
}
I have already written all the Parcelable code for single Tasks. But now I'm working on a new activity that requires an array of Tasks. On the one hand, I could create a TaskList
public class TaskList implements Parcelable {
List<Task> taskList;
// other stuff
}
but that means I would have to create a new object and rewrite a lot of Parcelable logic (even if it's almost identical). Instead it would be really nice if I could somehow just pass an array of Tasks. But the only function I see is this one.
public static final Parcelable.Creator<Task> CREATOR = new Parcelable.Creator<Task>() {
public Task createFromParcel(Parcel in) {
return new Task(in);
}
// This one......
public Task[] newArray(int size) {
return new Task[size];
}
// This one......
};
And I'm not really sure how Parceable would use this function to handle an array of Tasks. How can I pass an array of Tasks instead of creating a TaskList?
Upvotes: 4
Views: 4578
Reputation: 3914
first there is a plugin to generate parcelable code for your object, it will save your time, second all you need to do to pass parcelable array is to add it to intent by:
intent.putParcelableArrayListExtra(TASK_LIST,taskList);
you can find the plugin as explained in this screen shot
Upvotes: 4
Reputation: 1129
Suppose, you want to pass list from Activity A to B.
In Activity A :
intent.putParcelableArrayList("task_list", actualListObject);
In Activity B get data :
ArrayList<Task> receivedList = (Task) getIntent().getParcelableArrayList("task_list");
Upvotes: 2
Reputation: 15155
Do something like this to write an array list into Parcelable
:
public class Task implements Parcelable {
List<Task> taskList;
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeValue(taskList);
...
}
@SuppressWarnings("unchecked")
private Task(Parcel in) {
taskList = (List<Task>) in.readValue(List.class.getClassLoader());
...
}
}
It 100% works for me.
Upvotes: 2