How to pass object to activity in Android

How to pass an object to a new activity is among the common questions beginner android developers usually ask.

In the course of learning android application development, you will get to a point when you start to navigate from activity to activity and pass some data as the user navigates.

Passing data between activities is usually accomplish via Intent object. If you are new to android and still don’t know what an Intent is I will suggest you read about Intent in android documentation.

Android Intent has an attribute called extras. Extras is a bundle of any information. In real sense, it is just an additional information that supplement an Intent Action.

An intent object has a putExtras() method which accepts different primitive data types, array, bundle, serializable, parcelable and arraylist.

It is not possible to store a Java object in extras except if the class implements serializable or pracelable interface. Serializing or parceling an object in java help to preserve the state of the object.

Another option available to pass object to an activity is by converting a java object to a Json string using Gson library. You can then add the String the Intent extras. The String can be reconverted to Java object using fromJson() and toJson()methods

In this tutorial, we will focus on using Parcelable interface to convert our object to stream of data and store it in the intent bundle.

1. Create a Java Class that implements Parcelable

Create a new Java class and choose a name of your choice. Open the new Java file and add the code below.

import android.os.Parcel;
import android.os.Parcelable;

public class JavaObjects implements Parcelable {

    private String name;
    private String country;

    public JavaObjects(String name, String country) {
        this.name = name;
        this.country = country;
    }

    public JavaObjects(Parcel source){
        name = source.readString();
        country = source.readString();
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getCountry() {
        return country;
    }

    public void setCountry(String country) {
        this.country = country;
    }

    public static final Creator<JavaObjects> CREATOR = new Creator<JavaObjects>() {
        @Override
        public JavaObjects createFromParcel(Parcel in) {
            return new JavaObjects(in);
        }

        @Override
        public JavaObjects[] newArray(int size) {
            return new JavaObjects[size];
        }
    };

    @Override
    public int describeContents() {
        return 0;
    }

    @Override
    public void writeToParcel(Parcel dest, int flags) {
        dest.writeString(name);
        dest.writeString(country);
    }

    @Override
    public String toString() {
        return "JavaObjects{" +
                "name='" + name + '\'' +
                ", country='" + country + '\'' +
                '}';
    }
}

2. Create first Activity Class

Open the xml layout file of the new activity page and add the code below.

In the Activity class, we will add an instance of the  class to the intent extras.

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    android:orientation="vertical" 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"
    tools:context=".json.Json18">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Parcelable Objects"
        android:layout_gravity="center_horizontal"
        android:textSize="16sp"
        android:paddingBottom="16dp"/>

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Open"
        android:id="@+id/button"
        android:layout_gravity="center_horizontal"/>

</LinearLayout>

MainActivity.java

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;


public class Json18 extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_json18);

        Button button = findViewById(R.id.button);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(Json18.this, JsonActivity.class);
                intent.putExtra("Key",new JavaObjects("Peter", "Nigeria"));
                startActivity(intent);
            }
        });
    }
}

3. Create second Activity Class

The second Activity class will receive the Intent extras and convert the Parcelable extras to Java object. We will then display the content of the Java object to be sure it has retained the same data we passed.

JsonActivity.java

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.widget.TextView;


public class JsonActivity extends AppCompatActivity {

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_json_activity);

        Bundle bundle = getIntent().getExtras();
        JavaObjects javaObjects = bundle.getParcelable("Key");

        TextView textView = findViewById(R.id.text);
        TextView textView2 = findViewById(R.id.text2);
        TextView textView3 = findViewById(R.id.text3);
        textView.setText(javaObjects.toString());

        //Nested Object
        ContactInfo.Address contactInfo = getIntent().getParcelableExtra("key");
        textView2.setText(contactInfo.toString());

        //Nested Object with Date
        ContactInfo.Address date = getIntent().getParcelableExtra("date");
        textView3.setText(date.toString());
    }
}

activity_json_activity.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Receiving Objects from Another Activity"
        android:textSize="16sp"
        android:paddingBottom="16dp"
        android:layout_gravity="center_horizontal"/>

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textSize="20sp"
        android:textColor="@color/colorAccent"
        android:id="@+id/text"/>

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textSize="20sp"
        android:textColor="@color/colorAccent"
        android:id="@+id/text2"/>

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textSize="20sp"
        android:textColor="@color/colorAccent"
        android:id="@+id/text3"/>

</LinearLayout>

 

If you have any question or suggestions kindly use the comment box or you can contact us directly through our contact page below.

 

Add a Comment