Igor
Igor

Reputation: 6255

How do I pass an object between activities?

ALL,

Consider the following data structure:

class Foo
{
private int m1;
private double m2;
};

class Bar
{
private int m1;
private List<Foo> m2;
};

Now what I want to do is to pass Bar::m2 from one activity to another. The data in Bar are in the list view and selecting the row I need to pass an appropriate list m2 structure.

What is the best way to do it? What I tried is this:

Intent intent = new Intent();
intent.putExtra( "test", new ArrayList<Foo> );

but the receiving intent throws an exception "Parcelable: Unable to marshall"

AFAICT ArrayList should be serializable, so I don't understand why I'm getting an exception.

Can someone sched some light here please?

Thank you.

Upvotes: 1

Views: 75

Answers (3)

mihirjoshi
mihirjoshi

Reputation: 12201

Bundle bundle = new Bundle();
bundle.putSerializable("object", yourobject);
startActivity(new Intent(this,Myclass.class).putExtras(bundle);

your object class should implement Serializable or Parcelable.

class Foo implements Serializable
{
    /**
     * 
     */
    private static final long serialVersionUID = 1L;
    private int m1;
    private double m2;
};

class Bar implements Serializable
{
    /**
     * 
     */
    private static final long serialVersionUID = 1L;
    private int m1;
    private List<Foo> m2;
};

Upvotes: 1

CommonsWare
CommonsWare

Reputation: 1006674

AFAICT ArrayList should be serializable

Yes, but you don't have an ArrayList of nothing -- you have an ArrayList of Foo objects.

I don't understand why I'm getting an exception

Because Foo is not Serializable.

The efficient answer is for you to implement Parcelable support on Foo, then use putParcelableArrayListExtra() on your Intent.

The less-programming answer is for you to implement Serializable on Foo, in which case your current putExra() should work.

Upvotes: 3

Corey Horn
Corey Horn

Reputation: 499

You have to make your custom objects Seriablizable. Here is the documentation

Serializable

Upvotes: 1

Related Questions