Android – Pass Parcelable Object From One Activity to Another Using PutExtra
In this article, we are going to see how can we pass a Parcelable object from one activity to another activity and display the data on the second activity. To pass a Parcelable object from one activity to another in Android, we can use the putExtra() method of the Intent class and pass in the object as an argument to the second activity.
For Example:
MainActivity:
Kotlin
val objectt = Object() val intent = Intent( this , SecondActivity:: class .java) intent.putExtra( "object_key" , object) startActivity(intent) |
Java
Object objectt = new Object(); Intent intent = new Intent( this , SecondActivity. class ); intent.putExtra( "object_key" , objectt); startActivity(intent); |
SecondActivity:
Kotlin
val objectt = intent.getParcelableExtra<Employee>( "object_key" ) |
Java
Employee objectt = getIntent().getParcelableExtra( "object_key" ); |
Make sure that your data class must be implemented Parcelable interface. A sample video is given below to get an idea about what we are going to do in this article.
Step by Step Implementation
Step 1: Create a New Project in Android Studio
To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Kotlin as the programming language.
Step 2: Add buildFeatures to build.gradle (Module:app)
Since in this project, we used ViewBinding so we have to set ViewBinding=True.Navigate to Gradle Scripts > build.gradle (Module:app) and add the Below buildFeatures section under the android section in the build.gradle (Module:app).
buildFeatures { viewBinding = true }
Android Section
android { namespace 'com.example.w3wiki' compileSdk 33 defaultConfig { applicationId "com.example.w3wiki" minSdk 24 targetSdk 33 versionCode 1 versionName "1.0" testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner" } buildTypes { release { minifyEnabled false proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro' } } compileOptions { sourceCompatibility JavaVersion.VERSION_1_8 targetCompatibility JavaVersion.VERSION_1_8 } kotlinOptions { jvmTarget = '1.8' } buildFeatures { viewBinding = true } }
Step 3: Change the StatusBar Color
Navigate to app > res > values > themes > themes.xml and add the below code under the style section in the themes.xml file.
<item name="android:statusBarColor" tools:targetApi="l">#308d46</item>
Step 4: Creating a Data Class
In this step, we are going to create a Data class named Employee. Make sure that the class that we want to pass as a parseable must implement the Parcelable interface and also you should have to create a constructor with the Parcel parameter in order to read from the parcel and implement its members. Navigate to app > java > YourPackageName > Create a new data class named as Employee. below is the code for Employee.kt .
Kotlin
package com.example.w3wiki import android.os.Parcel import android.os.Parcelable // Employee Class data class Employee( val eid:Int, val name:String?, val email:String?, val mobile:String? ):Parcelable { // implementing parcelable interface constructor(parcel: Parcel) : this ( parcel.readInt(), parcel.readString(), parcel.readString(), parcel.readString() ) { } override fun describeContents(): Int { return 0 } override fun writeToParcel(parcel: Parcel, p1: Int) { parcel.writeInt(eid) parcel.writeString(name) parcel.writeString(email) parcel.writeString(mobile) } companion object CREATOR : Parcelable.Creator<Employee> { override fun createFromParcel(parcel: Parcel): Employee { return Employee(parcel) } override fun newArray(size: Int): Array<Employee?> { return arrayOfNulls(size) } } } |
Java
package com.example.w3wiki; import android.os.Parcel; import android.os.Parcelable; // Employee Class public class Employee implements Parcelable { private int eid; private String name; private String email; private String mobile; public Employee( int eid, String name, String email, String mobile) { this .eid = eid; this .name = name; this .email = email; this .mobile = mobile; } // implementing parcelable interface protected Employee(Parcel in) { eid = in.readInt(); name = in.readString(); email = in.readString(); mobile = in.readString(); } @Override public void writeToParcel(Parcel dest, int flags) { dest.writeInt(eid); dest.writeString(name); dest.writeString(email); dest.writeString(mobile); } @Override public int describeContents() { return 0 ; } public static final Creator<Employee> CREATOR = new Creator<Employee>() { @Override public Employee createFromParcel(Parcel in) { return new Employee(in); } @Override public Employee[] newArray( int size) { return new Employee[size]; } }; // Getter and Setter methods public int getEid() { return eid; } public void setEid( int eid) { this .eid = eid; } public String getName() { return name; } public void setName(String name) { this .name = name; } public String getEmail() { return email; } public void setEmail(String email) { this .email = email; } public String getMobile() { return mobile; } public void setMobile(String mobile) { this .mobile = mobile; } } |
In this code, we define a data class named as Employee that implements the Parcelable interface. The class has four properties (i,e: eid of type Int, name, email, and mobile of type String?. ) The class has a primary constructor with parameters for each of the properties, and an additional constructor that reads from a Parcel object passed as an argument. This allows for easy and efficient marshaling and unmarshalling of the object’s data when passed between activities. The writeToParcel method is used to write the contents of the object to the parcel, and the describeContents method is used to describe the contents of the parcel.
The CREATOR companion object is used to create an Array of Employee objects from a Parcel. The createFromParcel method reads the data from the parcel and constructs a new Employee object, and the newArray method creates a new array of Employee objects. Overall, this code provides a convenient and efficient way to pass the Employee object between activities, as well as to persist and restore its state.
Step 5: Working with activity_main.xml
Navigate to the app > res > layout > activity_main.xml and add the below code to the activity_main.xml file. Below is the code for the activity_main.xml file. The activity_main.xml represents the UI part of our MainActivity.
XML
<? xml version = "1.0" encoding = "utf-8" ?> <!--LinearLayout--> < LinearLayout xmlns:android = "http://schemas.android.com/apk/res/android" xmlns:app = "http://schemas.android.com/apk/res-auto" xmlns:tools = "http://schemas.android.com/tools" android:layout_width = "match_parent" android:layout_height = "match_parent" android:orientation = "vertical" android:gravity = "center" tools:context = ".MainActivity" > <!--Button--> < Button android:layout_width = "wrap_content" android:layout_height = "wrap_content" android:id = "@+id/btn_press" android:text = "Pass Object" /> </ LinearLayout > |
In this code a LinearLayout with a vertical orientation and gravity set to center, and a child Button element. The button has a layout width and height of “wrap_content”, an id of “btn_press”, and a text label of “Pass Object”.
Step 6: Working with the MainActivity File
In the MainActivity file, we implement all our functionality like applying OnClickListener to the Button and start a new activity. Go to the MainActivity File (Navigate to app > java > YourPackageName > MainActivity) and follow the below code. Comments are added inside the code for a better understanding of the Code.
Kotlin
package com.example.w3wiki import android.content.Intent import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import com.example.w3wiki.databinding.ActivityMainBinding class MainActivity : AppCompatActivity() { var bindings:ActivityMainBinding?= null companion object{ // Key that pass with intent var SECOND_ACTIVITY_CODE= "second_activity" } override fun onCreate(savedInstanceState: Bundle?) { super .onCreate(savedInstanceState) bindings=ActivityMainBinding.inflate(layoutInflater) setContentView(bindings?.root) // creating an object of the Employee class val employee= Employee( 1 , "Chinmaya Mohapatra" , "chinmaya@gmail.com" , "673298323" ) // Applying Onclick Listener to the Button bindings?.btnPress?.setOnClickListener { var intent= Intent( this @MainActivity ,SecondActivity:: class .java) // passing the object with key intent.putExtra(SECOND_ACTIVITY_CODE,employee) // start the second Activity startActivity(intent) } } } |
Java
package com.example.w3wiki; import androidx.appcompat.app.AppCompatActivity; import android.content.Intent; import android.os.Bundle; import android.view.View; import com.example.w3wiki.databinding.ActivityMainBinding; public class MainActivity extends AppCompatActivity { private ActivityMainBinding bindings; public static final String SECOND_ACTIVITY_CODE = "second_activity" ; @Override protected void onCreate(Bundle savedInstanceState) { super .onCreate(savedInstanceState); bindings = ActivityMainBinding.inflate(getLayoutInflater()); setContentView(bindings.getRoot()); // creating an object of the Employee class Employee employee = new Employee( 1 , "Chinmaya Mohapatra" , "chinmaya@gmail.com" , "673298323" ); // Applying OnClickListener to the Button bindings.btnPress.setOnClickListener( new View.OnClickListener() { @Override public void onClick(View view) { Intent intent = new Intent(MainActivity. this , SecondActivity. class ); // passing the object with key intent.putExtra(SECOND_ACTIVITY_CODE, employee); // start the second Activity startActivity(intent); } }); } } |
In this code when the button is clicked a new Intent is created and the employee object is passed to the SecondActivity class. The startActivity method is used to start the SecondActivity class.
Step 7: Creating Another Activity
In this Activity, we are going to receive the Employee class object passed by our MainActivity and display it in our UI elements. Navigate to app > java > YourPackageName > Create a new Activity named as SecondActivity. Below is the code for SecondActivity.kt.
Kotlin
package com.example.w3wiki import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import com.example.w3wiki.databinding.ActivitySecondBinding class SecondActivity : AppCompatActivity() { var binding:ActivitySecondBinding?= null override fun onCreate(savedInstanceState: Bundle?) { super .onCreate(savedInstanceState) binding= ActivitySecondBinding.inflate(layoutInflater) setContentView(binding?.root) // creating a nullable Employee class object var employeeModel:Employee?= null // check if the Employee class hasExtra if (intent.hasExtra(MainActivity.SECOND_ACTIVITY_CODE)){ // getting the Parcelable object into the employeeModel employeeModel= intent.getParcelableExtra(MainActivity.SECOND_ACTIVITY_CODE) } // if the employeeModel is not null then display the data if (employeeModel != null ) { binding?.tvEId?.text=employeeModel.eid.toString() binding?.tvEname?.text=employeeModel.name binding?.tvEEmail?.text=employeeModel.email binding?.tvEMobile?.text=employeeModel.mobile } } } |
Java
package com.example.w3wiki; import androidx.appcompat.app.AppCompatActivity; import android.content.Intent; import android.os.Bundle; import com.example.w3wiki.databinding.ActivitySecondBinding; public class SecondActivity extends AppCompatActivity { private ActivitySecondBinding binding; @Override protected void onCreate(Bundle savedInstanceState) { super .onCreate(savedInstanceState); binding = ActivitySecondBinding.inflate(getLayoutInflater()); setContentView(binding.getRoot()); // creating a nullable Employee class object Employee employeeModel = null ; // check if the Employee class hasExtra if (getIntent().hasExtra(MainActivity.SECOND_ACTIVITY_CODE)) { // getting the Parcelable object into the employeeModel employeeModel = getIntent().getParcelableExtra(MainActivity.SECOND_ACTIVITY_CODE); } // if the employeeModel is not null then display the data if (employeeModel != null ) { binding.tvEId.setText(Integer.toString(employeeModel.getEid())); binding.tvEname.setText(employeeModel.getName()); binding.tvEEmail.setText(employeeModel.getEmail()); binding.tvEMobile.setText(employeeModel.getMobile()); } } } |
In this code It creates a nullable variable employeeModel of type Employee data class. Then it checks if the Intent that started this activity contains the SECOND_ACTIVITY_CODE extra. If the extra exists, it uses the getParcelableExtra() method to get the Employee Parcelable object passed from the MainActivity. If the employeeModel is not null, it sets the text of several TextView elements in the layout to the properties of the Employee object. This activity is used to display the information of the employee object passed from the MainActivity.
Step 8: Working with activity_second.xml
Navigate to the app > res > layout > activity_second.xml and add the below code to the activity_second.xml file. Below is the code for the activity_second.xml file. The activity_second.xml represents the UI part of our SecondActivity.
XML
<? xml version = "1.0" encoding = "utf-8" ?> <!--LinearLayout vertical--> < LinearLayout xmlns:android = "http://schemas.android.com/apk/res/android" xmlns:app = "http://schemas.android.com/apk/res-auto" xmlns:tools = "http://schemas.android.com/tools" android:layout_width = "match_parent" android:layout_height = "match_parent" android:orientation = "vertical" android:gravity = "center" tools:context = ".SecondActivity" > <!--LinearLayout Horizontal--> < LinearLayout android:layout_width = "match_parent" android:layout_height = "wrap_content" android:orientation = "horizontal" android:gravity = "center" > < TextView android:layout_width = "wrap_content" android:layout_height = "wrap_content" android:id = "@+id/tv_eIddisplay" android:text = "Employee ID : " android:gravity = "center" android:textStyle = "bold" android:textSize = "20sp" android:textColor = "@color/black" android:layout_margin = "10dp" /> < TextView android:layout_width = "wrap_content" android:layout_height = "wrap_content" android:id = "@+id/tv_eId" android:text = "Id" android:gravity = "center" android:textSize = "20sp" android:textColor = "@color/black" /> </ LinearLayout > <!--LinearLayout Horizontal--> < LinearLayout android:layout_width = "match_parent" android:layout_height = "wrap_content" android:orientation = "horizontal" android:gravity = "center" > < TextView android:layout_width = "wrap_content" android:layout_height = "wrap_content" android:id = "@+id/tv_namedisplay" android:text = "Employee Name : " android:gravity = "center" android:textStyle = "bold" android:textSize = "20sp" android:textColor = "@color/black" android:layout_margin = "10dp" /> < TextView android:layout_width = "wrap_content" android:layout_height = "wrap_content" android:id = "@+id/tv_ename" android:text = "name" android:gravity = "center" android:textSize = "20sp" android:textColor = "@color/black" /> </ LinearLayout > <!--LinearLayout Horizontal--> < LinearLayout android:layout_width = "match_parent" android:layout_height = "wrap_content" android:orientation = "horizontal" android:gravity = "center" > < TextView android:layout_width = "wrap_content" android:layout_height = "wrap_content" android:id = "@+id/tv_eemaildisplay" android:text = "Email ID : " android:gravity = "center" android:textStyle = "bold" android:textSize = "20sp" android:textColor = "@color/black" android:layout_margin = "10dp" /> < TextView android:layout_width = "wrap_content" android:layout_height = "wrap_content" android:id = "@+id/tv_eEmail" android:text = "Email" android:gravity = "center" android:textSize = "20sp" android:textColor = "@color/black" /> </ LinearLayout > <!--LinearLayout Horizontal--> < LinearLayout android:layout_width = "match_parent" android:layout_height = "wrap_content" android:orientation = "horizontal" android:gravity = "center" > < TextView android:layout_width = "wrap_content" android:layout_height = "wrap_content" android:id = "@+id/tv_eMobiledisplay" android:text = "Mobile No : " android:gravity = "center" android:textStyle = "bold" android:textSize = "20sp" android:textColor = "@color/black" android:layout_margin = "10dp" /> < TextView android:layout_width = "wrap_content" android:layout_height = "wrap_content" android:id = "@+id/tv_eMobile" android:text = "Mobile" android:gravity = "center" android:textSize = "20sp" android:textColor = "@color/black" /> </ LinearLayout > </ LinearLayout > |
Output:
Contact Us