MalcomTucker
MalcomTucker

Reputation: 7477

How to send custom data objects with Intents in Android?

Intents in Android are an elegant way to pass messages between uncoupled components, but what if you want to send extra data with the Intent? I know you can add various value types, and objects that implement Parcelable, as extras, but this doesn't really cater for sending user defined types locally (i.e. not over a remote interface). Any ideas?

Upvotes: 6

Views: 3833

Answers (3)

Dan
Dan

Reputation: 811

In your type, you can implement the Serializable interface and call the Intent.putExtra(String, Serializable) method to include it in the intent. I considered doing it myself for a similar problem, but opted to just put the data in a bundle because my type would only have had two fields and it just wasn't worth the effort.

This is how it could work, assuming that you have implemented Serializable on Foo:

Foo test = new Foo();
test.Name = "name";
test.Value = "value";

Intent intent = new Intent();
intent.putExtra("test", test);

Upvotes: 4

Josef Pfleger
Josef Pfleger

Reputation: 74507

If you want to pass objects within a single process you can implement your own Application to maintain global state:

Base class for those who need to maintain global application state. You can provide your own implementation by specifying its name in your AndroidManifest.xml's tag, which will cause that class to be instantiated for you when the process for your application/package is created.

Upvotes: 1

Suresh
Suresh

Reputation: 9595

When you say locally, does that mean sending the user defined types across the Activities/ local Services that belongs to same APK? As long as user-defined type is parcelable it can be sent as extras in intent and can be processed in onStartCommand() of service/activity.

Upvotes: 0

Related Questions