Search code examples
androidarraysparcelable

Android: Can I pass an array of Parcelable objects? Do I need to create a wrapper object?


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?


Solution

  • 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.