Passing an object from an Activity to another

The method startActivity(Intent intent) of the class Activity allows you to call a second activity specified using the argument Intent.
You can associate primitive data or primitive data array to the argument Intent and then the second Activity can access them, you can also pass objects of type String using methods of the class Bundle like put*().
In this post I show an example to pass a more complex object between an Activity and another.

Suppose to pass an object Contact like this:

The first step is to implement the Parcelable interface

that requires

  • a field CREATOR, public, static and that implements Parcelable.Creator, and I the following is a standard implementation for the Contact class

    where YourClass is Contact in my example
  • the previous step requires the presence of a constructor
  • the method writeToParcel, to save the fields firstname and lastname

    it is important that the data read in the method readFromParcel are of the same type and in the same order of those written in the method writeToParcel
  • the method describeContents, and its usual implementation is:

    I don’t understand the function of this method, and I don’t know when it should return a value other than 0

Now the class Contact is ready to be passed from one activity to another, the code to insert into the calling activity is

where SecondActivity is the called activity, that receives and handles the object Contact with the code:

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.