简体   繁体   中英

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.

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 .

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM