Send Data From one Activity to Another Using Parcelable in Android Java

In this article, we will learn how to send data from one Activity to Another using Parcelable in Android Java. At the end of this tutorial, you will see the following screen will be designed.

Enter data from one Activity using Parcelable - Handy Opinion

Parcelable is a pure Android interface. It allows developers to serialize a class. Its properties can be easily transferred from one activity to another. It does this by reading and writing objects from packages that can contain flat data in message containers.

Retrive data on one Activity using Parcelable - Handy Opinion

Main Activity

Main Activity handles the collection of the book details. Let’s start by setting up our onCreate method.

package com.example.parcelable;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

public class MainActivity extends AppCompatActivity {

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

Now open your MainActivity.java file and then you have to link the view fields to your activity. You have to do it inside your onCreate() method, as shown below

final EditText mBkTitle = (EditText) findViewById(R.id.title);
final EditText mBkAuthor = (EditText) findViewById(R.id.author);
Button button = (Button) findViewById(R.id.submit_button);

In the MainActivity.Java file, you need to set up an onClickListener and this function call when you click the Submit button.

button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                Book book = new Book(mBkTitle.getText().toString(),
                        mBkAuthor.getText().toString());

                Intent intent = new Intent(MainActivity.this, BookActivity.class);
                intent.putExtra("Book", book);
                startActivity(intent);
            }
        });

Create the Book Class

Let create a Book class to hold information about each book. This class needs to implement Parcelable. This will enable the passing of the data from MainActivity to BookActivity.

package com.example.parcelable;

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

public class Book implements Parcelable {
    // book basics
    private String title;
    private String author;

    // main constructor
    public Book(String title, String author) {
        this.title = title;
        this.author = author;
    }

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

    public static final Parcelable.Creator<Book> CREATOR = new Parcelable.Creator<Book>() {

        @Override
        public Book createFromParcel(Parcel parcel) {
            return new Book(parcel);
        }

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

    // getters
    public String getTitle() { return title; }
    public String getAuthor() { return author; }

    // write object values to parcel for storage
    public void writeToParcel(Parcel dest, int flags) {
        dest.writeString(title);
        dest.writeString(author);
    }

    public Book(Parcel parcel) {
        title = parcel.readString();
        author = parcel.readString();
    }
}

Write to the Parcel

Use the writeToParcel method to add all of your class data to the package. This method is passed to a package instance that has a number of write methods that allow you to add any field to the package.

// write object values to parcel for storage
    public void writeToParcel(Parcel dest, int flags) {
        dest.writeString(title);
        dest.writeString(author);
    }

Read Data From the Parcel

The write method handles writing the data to be transferred, the constructor is used to read the transferred data from the serialized package. This method is called on the receiving activity to collect the data.

public Book(Parcel parcel) {
        title = parcel.readString();
        author = parcel.readString();
    }

Parcelable.Creator

As you can see in the above Book Model class, you need to create an Parcelable.Creator instance and assign it to the CREATOR field.  The Parcelable API looks for the field when it requires to deserialize an instance of your class and that has been passed to another component.

public static final Parcelable.Creator<Book> CREATOR = new Parcelable.Creator<Book>() {

        @Override
        public Book createFromParcel(Parcel parcel) {
            return new Book(parcel);
        }

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

Conclusion

In this article, you see how to send data from one activity to another. You no longer have to load each data field individually on the intended object and you no longer have to remember the name under which each field was approved. Also, this process is faster than Serializer.

In this tutorial, you have learned how to use parcels to transfer data from one activity to another. For more information on parcels, see the official documentation.

If you have any questions or suggestions, feel free to ask in the comments section below.

Next Article

Send Data From one Activity to Another Using Parcelable in Kotlin

Please share this post:
Posts created 41

Ask a Question

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

Related Posts

Begin typing your search term above and press enter to search. Press ESC to cancel.

%d bloggers like this: