How to Pass Data Between Activities in Android Application

Introduction

In an Android application, it is often necessary to pass data between different activities. One common scenario is when you have a login page and want to pass the session id of the logged-in user to other activities. This can be achieved by using the Intent class to pass data between activities.

Using Intent to Pass Data

The Intent class in Android is used to navigate or communicate between different components of an application, such as activities, services, and broadcast receivers. It provides a way to pass both primitive data types and complex objects between activities.

Passing Primitive Data Types

To pass primitive data types, such as strings, integers, or booleans, between activities, you can use the putExtra() method of the Intent class.


Intent intent = new Intent(this, SecondActivity.class);
intent.putExtra("session_id", sessionId);
startActivity(intent);
        

In the above code snippet, we create an Intent object and specify the source activity (this) and the destination activity (SecondActivity). We then use the putExtra() method to add the session_id as an extra to the intent, along with its value (sessionId). Finally, we start the activity by calling startActivity(intent).

In the receiving activity (SecondActivity), we can retrieve the passed data using the getIntent() method and then access the extra data using the getExtras() method.


Intent intent = getIntent();
Bundle extras = intent.getExtras();
if (extras != null) {
    String sessionId = extras.getString("session_id");
}
        

In this code snippet, we retrieve the intent using getIntent() and then get the extras using getExtras(). We check if the extras is not null before accessing the session_id value using getString().

Passing Complex Objects

If you need to pass complex objects between activities, you can make the object implement the Parcelable interface. This requires implementing the writeToParcel() method to write the object's data to a Parcel and the CREATOR field to create the object from a Parcel.

For example, let's say we have a User object with the following fields:


public class User implements Parcelable {
    private String name;
    private int age;

    // Constructor, getters, and setters

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

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

    public static final Parcelable.Creator<User> CREATOR = new Parcelable.Creator<User>() {
        public User createFromParcel(Parcel in) {
            return new User(in);
        }

        public User[] newArray(int size) {
            return new User[size];
        }
    };

    private User(Parcel in) {
        name = in.readString();
        age = in.readInt();
    }
}
        

In this code snippet, the User object implements the Parcelable interface. We override the describeContents() method and return 0, indicating that our object doesn't have any special objects contained within it that need to be written to the Parcel. We also override the writeToParcel() method to write the object's fields to the Parcel.

We also define a CREATOR field, which is a Parcelable.Creator object that can be used to recreate the object from a Parcel. We implement the createFromParcel() method to read the fields from the Parcel and create a new User object.

Now, we can pass a User object between activities using the putExtra() method:


User user = new User("John Doe", 25);
Intent intent = new Intent(this, SecondActivity.class);
intent.putExtra("user", user);
startActivity(intent);
        

In the receiving activity, we can retrieve the User object using the getParcelableExtra() method:


Intent intent = getIntent();
User user = intent.getParcelableExtra("user");
        

Alternative to Passing Data between Activities

While using Intent to pass data between activities is a common and effective approach, there are alternative methods available:

  • Using a Singleton class: You can create a Singleton class to hold the session id and access it from any activity in your application. This approach ensures that only one instance of the class is created throughout the application's lifecycle.
  • Using SharedPreferences: The SharedPreferences class allows you to store key-value pairs persistently. You can store the session id in SharedPreferences and access it from any activity in your application.
  • Using a Database: If you have a large amount of data to pass between activities or need to persist the data, you can store it in a database and retrieve it as needed.

Each alternative has its own pros and cons, and the choice depends on the specific requirements of your application.

Conclusion

In this article, we have explored how to pass data between activities in an Android application. We have discussed using Intent to pass both primitive data types and complex objects between activities. We have also explored alternative methods for passing data. By understanding and implementing these techniques, you can effectively pass data between activities in your Android application.