Gen
Gen

Reputation: 403

Android, How to put an ArrayList<myObject> in an Intent?

I have two Activities, in the first one, I instanciate an ArrayList of Object myObject. In the second activity, i need to get this Arraylist. I don't know how to do that with an intent ?

(Object is a class I have created)

Thanks in advance.

Upvotes: 6

Views: 15386

Answers (4)

Rasel
Rasel

Reputation: 5734

I used like this.

put:

intent.putExtra("data", new DataWrapper(selectedTasks));
startActivity(intent);

get:

DataWrapper dw = (DataWrapper) getIntent().getSerializableExtra("data");
ArrayList<SelectedTask> taskList = dw.getList();

Arraylist object should be Serializable

public class SelectedTask implements Serializable{

}

public class DataWrapper implements Serializable{
    private ArrayList<SelectedTask> slist;

       public DataWrapper(ArrayList<SelectedTask> data) {
          this.slist = data;
       }

       public ArrayList<SelectedTask> getList() {
          return this.slist;
       }
}

Upvotes: 0

getekha
getekha

Reputation: 2583

If you make your Object class implement Parcelabel you can pack your arraylist into the bundle you send with the intent

see this link for an example

Upvotes: 6

ccheneson
ccheneson

Reputation: 49410

Your class myObject will have to implement Parcelable. Then, you can use putParcelableArrayListExtra from your intent to pass it to the next activity and retrieve the list with getParcelableArrayListExtra

Upvotes: 1

Mark Fisher
Mark Fisher

Reputation: 9886

Usually you use Bundle objects to pass information between Activities, but these only allow for simple type objects. Typically, for passing more complex object types you generally have to construct a static context of some kind and set your values on that, which is then available to the second activity. It feels dirty, but I've got over it in my apps now.

Upvotes: 1

Related Questions