Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to send custom data objects with Intents in Android?

Tags:

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?

like image 398
MalcomTucker Avatar asked Jul 30 '10 15:07

MalcomTucker


People also ask

How can we send object using Intent?

One way to pass objects in Intents is for the object's class to implement Serializable. This interface doesn't require you to implement any methods; simply adding implements Serializable should be enough. To get the object back from the Intent, just call intent.

How do you pass custom objects using Intent in Kotlin?

Simple move your cursor to "People" and hit alt+enter. It should now show the option to generate a Parcelable implementation.

How do I transfer data from one Intent to another?

Using Intents This example demonstrate about How to send data from one activity to another in Android using intent. Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project. Step 2 − Add the following code to res/layout/activity_main. xml.


2 Answers

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);
like image 94
Dan Avatar answered Oct 28 '22 04:10

Dan


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.

like image 29
Josef Pfleger Avatar answered Oct 28 '22 03:10

Josef Pfleger