How to Implement and Use a Parcelable Class in Android: Part 2
Welcome to Part 2!
Hi! In this article we will use the parcelable class we created in Part 1 to pass an object from the MainActivity
to the DetailsActivity
. Let’s begin!
💡 Tips: This is the second article in this series on How to Implement a Parcelable Class. This is Part 1:
Demo App
This is the App we are going to build, it has an extremely simple UI to focus on the aspects of the parcelable object.
- In the
MainActivity
we create an instance ofHouse
. - If we click on the
Launch Details
Button the parcelable object is passed to to theDetailsActivity
. - The
DetailsActivity
is launched and the data for the object is read and displayed.
Passing a Parcelable Object between Activities
Creating an Instance of the Parcelable object
For this demo I created an instance of House
in the onCreate
method:
house1 = new House(100000, "Los Angeles", true, previousOwnersArray);
Launching Details Activity
In MainActivity
you need to launch DetailsActivity
by passing the instance of the parcelable object as an extra.
public void launchDetailsActivity(House house) {
Intent intent = new Intent(this, DetailsActivity.class);
intent.putExtra(HOUSE_KEY, house);
startActivity(intent);
}
⚠️ Note: Notice that I used HOUSE_KEY
as the key for the extra that contains the parcelable object. This is a string variable that I previously defined in the class and you need to use this same string to read the object in the destination Activity.
Final Code
This is the final code for MainActivity
:
Reading the Object in Details Activity
To read the object in the destination Activity and save it to a variable we use this syntax.
house = getIntent().getParcelableExtra(HOUSE_KEY);
💡 Tips: Notice that HOUSE_KEY
is the same key we used to send the extra from MainActivity
.
After this, we can use the variable house
in our DetailsActivity
and access its getters and setters.
This is the final code for DetailsActivity
:
👏 I really hope you’ve found this series helpful. Your claps are really appreciated to help others find this article 😃 . Thank you very much in advance!