Android Pass Custom Object In Intent Example

This article will tell you how to pass custom-type objects via intent between two android activities. It is not difficult, you just need to make your custom class either implements the java.io.Serializable or android.os.Parcelable interface.

1. Android Pass Object Via Intent Between Activity Example Overview.

If you can not watch the above video, you can see it on the youtube URL https://youtu.be/ImFqs2dBs_M

  1. There are two activities in this example.
  2. User input some info in the first activity, when he clicks the submit button, the input data will be passed to the target activity with intent. And the data is saved in the intent with a custom-type object.
  3. Below is the example used java files. UserAccountDTO is a class that implements java.io.Serializable. And UserDepartmentDTO is a custom class that implements android.os.Parcelable.
    D:\WORK\DEV2QA.COM-EXAMPLE-CODE\ANDROIDEXAMPLEPROJECT\EXAMPLE\APP\SRC\MAIN\JAVA\COM\DEV2QA\EXAMPLE\INTENT
    └─pass_object
            IntentPassObjectActivity.java
            IntentPassObjectTargetActivity.java
            UserAccountDTO.java
            UserDepartmentDTO.java

2. Main Activity.

  1. IntentPassObjectActivity.java
    package com.dev2qa.example.intent.pass_object;
    
    import android.content.Intent;
    import android.os.Bundle;
    import android.support.v7.app.AppCompatActivity;
    import android.view.View;
    import android.widget.Button;
    import android.widget.EditText;
    
    import com.dev2qa.example.R;
    
    public class IntentPassObjectActivity extends AppCompatActivity {
    
        public static final String INTENT_PARAM_KEY_USER_ACCOUNT = "INTENT_PARAM_KEY_USER_ACCOUNT";
    
        public static final String INTENT_PARAM_KEY_USER_DEPARTMENT = "INTENT_PARAM_KEY_USER_DEPARTMENT";
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_intent_pass_object);
    
            setTitle("dev2qa.com - Android Intent Pass Object Example.");
    
            Button submitButton = (Button)findViewById(R.id.intent_pass_object_submit_button);
    
            submitButton.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    // Get user input data.
                    EditText userNameEditText = (EditText)findViewById(R.id.intent_pass_object_username);
                    EditText passwordEditText = (EditText)findViewById(R.id.intent_pass_object_password);
                    EditText departmentEditText = (EditText)findViewById(R.id.intent_pass_object_department);
                    EditText titleEditText = (EditText)findViewById(R.id.intent_pass_object_title);
    
                    String userName = userNameEditText.getText().toString();
                    String password = passwordEditText.getText().toString();
                    String department = departmentEditText.getText().toString();
                    String title = titleEditText.getText().toString();
    
                    // Create user account dto.
                    UserAccountDTO userAccountDto = new UserAccountDTO();
                    userAccountDto.setUserName(userName);
                    userAccountDto.setPassword(password);
    
                    // Crete user department dto.
                    UserDepartmentDTO userDepartmentDto = new UserDepartmentDTO();
                    userDepartmentDto.setUserName(userName);
                    userDepartmentDto.setDepartment(department);
                    userDepartmentDto.setTitle(title);
    
                    // Create intent.
                    Intent intent = new Intent(IntentPassObjectActivity.this, IntentPassObjectTargetActivity.class);
             
                    // Put above two dto in the intent as usual.
                    intent.putExtra(INTENT_PARAM_KEY_USER_ACCOUNT, userAccountDto);
                    intent.putExtra(INTENT_PARAM_KEY_USER_DEPARTMENT, userDepartmentDto);
                    // Start the target activity.
                    startActivity(intent);
                }
            });
    
        }
    }

3. Target Activity.

  1. IntentPassObjectTargetActivity.java
    package com.dev2qa.example.intent.pass_object;
    
    import android.content.Intent;
    import android.os.Bundle;
    import android.support.v7.app.AppCompatActivity;
    import android.widget.TextView;
    
    import com.dev2qa.example.R;
    
    public class IntentPassObjectTargetActivity extends AppCompatActivity {
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_intent_pass_object_target);
    
            setTitle("dev2qa.com - This Is The Target Activity.");
    
            Intent intent = getIntent();
    
            /* Call intent getSerializableExtra method to get object 
               that implement java.io.Serializable interface.
             */
            Object userAccountObj = intent.getSerializableExtra(IntentPassObjectActivity.INTENT_PARAM_KEY_USER_ACCOUNT);
            UserAccountDTO userAccountDto = (UserAccountDTO)userAccountObj;
    
            /* Call intent getParcelableExtra method to get object 
               that implement android.os.Parcelable interface. */
            Object userDepartmentObj = intent.getParcelableExtra(IntentPassObjectActivity.INTENT_PARAM_KEY_USER_DEPARTMENT);
            UserDepartmentDTO userDepartmentDto = (UserDepartmentDTO)userDepartmentObj;
    
            StringBuffer userInfoBuf = new StringBuffer();
            userInfoBuf.append("UserName : ");
            userInfoBuf.append(userAccountDto.getUserName());
    
            userInfoBuf.append("\r\nPassword : ");
            userInfoBuf.append(userAccountDto.getPassword());
    
            userInfoBuf.append("\r\nDepartment : ");
            userInfoBuf.append(userDepartmentDto.getDepartment());
    
            userInfoBuf.append("\r\nTitle : ");
            userInfoBuf.append(userDepartmentDto.getTitle());
    
            TextView targetTextView = (TextView)findViewById(R.id.intent_pass_object_target_text_view);
            targetTextView.setText(userInfoBuf.toString());
        }
    }

4. UserAccountDTO.java

  1. This class implements the java.io.Serializable interface.
    package com.dev2qa.example.intent.pass_object;
    
    import java.io.Serializable;
    
    public class UserAccountDTO implements Serializable {
    
        private String userName;
    
        private String password;
    
        public String getUserName() {
            return userName;
        }
    
        public void setUserName(String userName) {
            this.userName = userName;
        }
    
        public String getPassword() {
            return password;
        }
    
        public void setPassword(String password) {
            this.password = password;
        }
    }

5. UserDepartmentDTO.java

  1. This class implements the android.os.Parcelable interface.
  2. It must override some abstract methods and it must have an android.os.Parcelable.Creator type instance variable, the variable name must be CREATOR, and CREATOR must be declared as public static final.
    package com.dev2qa.example.intent.pass_object;
    
    import android.os.Parcel;
    import android.os.Parcelable;
    
    
    public class UserDepartmentDTO implements Parcelable {
    
        private String userName;
    
        private String department;
    
        private String title;
    
        @Override
        public int describeContents() {
            return 0;
        }
    
        /* This method is used to write instance variable to Parcel.*/
        @Override
        public void writeToParcel(Parcel dest, int flags) {
            dest.writeString(userName);
            dest.writeString(department);
            dest.writeString(title);
        }
    
        /* Must create this static class variable to make this class Parcelable. */
        public static final Creator<UserDepartmentDTO> CREATOR = new Creator<UserDepartmentDTO>()
        {
            @Override
            public UserDepartmentDTO createFromParcel(Parcel source) {
                UserDepartmentDTO ret = new UserDepartmentDTO();
    
                //The read order should be same as write order in writeToParcel method.
                ret.userName = source.readString();
                ret.department = source.readString();
                ret.title = source.readString();
    
                return ret;
            }
    
            @Override
            public UserDepartmentDTO[] newArray(int size) {
                return new UserDepartmentDTO[size];
            }
        };
    
        public String getUserName() {
            return userName;
        }
    
        public void setUserName(String userName) {
            this.userName = userName;
        }
    
        public String getDepartment() {
            return department;
        }
    
        public void setDepartment(String department) {
            this.department = department;
        }
    
        public String getTitle() {
            return title;
        }
    
        public void setTitle(String title) {
            this.title = title;
        }
    }

6. Main Activity Layout Xml File.

  1. It uses TableLayout to implement a user input interface.
  2. activity_intent_pass_object.xml
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical">
    
        <TableLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:padding="35dp">
    
            <!-- User name row. -->
            <TableRow
                android:layout_width="match_parent"
                android:layout_height="match_parent" >
    
                <TextView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text="User Name:"
                    android:gravity="right"/>
                <EditText
                    android:id="@+id/intent_pass_object_username"
                    android:ems="10" />
            </TableRow>
    
            <!-- Password row. -->
            <TableRow
                android:layout_width="match_parent"
                android:layout_height="match_parent" >
    
                <TextView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text="Password:"
                    android:gravity="right"/>
                <EditText
                    android:id="@+id/intent_pass_object_password"
                    android:inputType="textPassword"
                    android:ems="10"/>
    
            </TableRow>
    
            <!-- Department row. -->
            <TableRow
                android:layout_width="match_parent"
                android:layout_height="match_parent" >
    
                <TextView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text="Department:"
                    android:gravity="right"/>
                <EditText
                    android:id="@+id/intent_pass_object_department"
                    android:ems="10"/>
            </TableRow>
    
            <!-- Title row. -->
            <TableRow
                android:layout_width="match_parent"
                android:layout_height="match_parent" >
    
                <TextView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text="Title:"
                    android:gravity="right"/>
                <EditText
                    android:id="@+id/intent_pass_object_title"
                    android:ems="10"/>
            </TableRow>
    
        </TableLayout>
    
        <Button
            android:id="@+id/intent_pass_object_submit_button"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="right"
            android:layout_marginRight="90dp"
            android:text="Submit"/>
    
    </LinearLayout>

7. Target Activity Layout Xml File.

  1. activity_intent_pass_object_target.xml
    <TextView
        android:id="@+id/intent_pass_object_target_text_view"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_margin="35dp"
        android:textSize="20dp"/>
0 0 votes
Article Rating
Subscribe
Notify of
guest

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

0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x