Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 208
Cameron Avatar asked Oct 20 '25 17:10

Cameron


2 Answers

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 enter image description here

like image 102
Mohamed Ibrahim Avatar answered Oct 22 '25 07:10

Mohamed Ibrahim


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.

like image 35
Anggrayudi H Avatar answered Oct 22 '25 05:10

Anggrayudi H