user1400312
user1400312

Reputation:

Passing arbitrary object in Android Intent

I wish to pass an arbitary object via an Android intent, I have the following code:

In the activity I wish to send an intent from:

Intent intent = new Intent(containerListActivity, com.uk.jacob.containerdroid.activities.ContainerDetailsActivity.class);
intent.putExtra("container", containers.get(i));
containerListActivity.startActivity(intent);

The activity I wish to recieve an intent:

System.out.println(getIntent().getExtras("container"));

I seem to get the error "cannot resolve method putExtra.

containers is essentially a Jackson JSON mapped POJO.

Upvotes: 2

Views: 974

Answers (2)

chessdork
chessdork

Reputation: 2019

Unfortunately, you can't put an arbitrary object in the Intent. It needs to be Parcelable or Serializable.

http://developer.android.com/reference/android/content/Intent.html

You can do it a few ways:

  1. Have your custom class implement Serializable. This is quick to code, but may not be performant.
  2. Have your custom class implement Parcelable. This could be a bit of work.
  3. Convert your container to a string using Jackson, then convert it back after using getStringExtra.

Upvotes: 3

frogatto
frogatto

Reputation: 29285

Serialize your JSON to a string and then push it to the intent. In the receiving activity try getStringExtra() to extract it from the intent object.

Upvotes: 1

Related Questions