Parcelable interface in Android

Parcelable interface in Android

In Android, the Parcelable interface is a mechanism for implementing object serialization and deserialization. It allows us to convert custom Java objects into a transportable binary data stream to pass data between different components. Usually when passing complex custom objects between activities, it is more efficient to use the Parcelable interface than to use Java's Serializable interface.

The Parcelable interface works by splitting an object's data into primitive data types and serializing and deserializing them when writing and reading. This avoids using Java's reflection mechanism and improves performance.

To implement the Parcelable interface, you first need to have a custom Java class implement the Parcelable interface and implement the following methods:

  1. writeToParcel(Parcel parcel, int flags): Write the object's data to the Parcel object for serialization. In this method, each field of the object needs to be written to the Parcel object.

  2. createFromParcel(Parcel parcel): Read data from Parcel object for deserialization. In this method, you need to read the data in Parcel and set it to each field of the object.

  3. newArray(int size): Create an object array of specified size, usually used in the deserialization process.

Next, you need to add a static Parcelable.Creator object to the class for creating and deserializing objects. This object needs to implement the Parcelable.Creator interface and implement the following methods:

  1. createFromParcel(Parcel parcel): Create and return an object instance based on the Parcel object.

  2. newArray(int size): Create an object array of specified size.

Finally, add a public static final Parcelable.Creator object to the class for system use.

Here is a simple example that demonstrates how to implement the Parcelable interface in Android:

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

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

    public Student(String name, int age) {
    
    
        this.name = name;
        this.age = age;
    }

    protected Student(Parcel in) {
    
    
        name = in.readString();
        age = in.readInt();
    }

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

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

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

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

In this example, we created a class named Student that implements the Parcelable interface. In the writeToParcel method, we write the name and age fields of the Student object into the Parcel object. In the createFromParcel method, we read the name and age fields from the Parcel object and create a new Student object.

By implementing the Parcelable interface, we can pass Student objects between different Android components without the need for cumbersome serialization and deserialization operations. At the same time, the Parcelable interface is more efficient than the Serializable interface and is suitable for use in scenarios with high performance requirements.

Code examples

When using Parcelableinterfaces, we can pass custom Java class objects to Android components, such as between Activities. Here is a simple example showing how to implement Parcelableinterfaces and pass custom objects between activities:

First, create a StudentJava class called which contains some basic fields and methods:

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

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

    public Student(String name, int age) {
    
    
        this.name = name;
        this.age = age;
    }

    protected Student(Parcel in) {
    
    
        name = in.readString();
        age = in.readInt();
    }

    public String getName() {
    
    
        return name;
    }

    public int getAge() {
    
    
        return age;
    }

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

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

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

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

Next, in the sender's Activity, we create an Studentobject and Intentpass it to the receiver's Activity using:

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;

public class SenderActivity extends AppCompatActivity {
    
    

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

        // 创建一个Student对象
        Student student = new Student("Alice", 20);

        // 使用Intent传递Student对象给ReceiverActivity
        Intent intent = new Intent(this, ReceiverActivity.class);
        intent.putExtra("student", student);
        startActivity(intent);
    }
}

Finally, in the receiver's Activity, we get the passed Studentobject from the Intent:

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;

public class ReceiverActivity extends AppCompatActivity {
    
    

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

        // 从Intent中获取传递过来的Student对象
        Student student = getIntent().getParcelableExtra("student");

        if (student != null) {
    
    
            // 使用Student对象的数据
            String name = student.getName();
            int age = student.getAge();

            // 在这里进行相关操作,例如显示学生信息
        }
    }
}

By implementing Parcelableinterfaces, we can easily pass custom Studentobjects between Activities without requiring additional serialization and deserialization operations. In the receiver's Activity, we can obtain the passed Studentobject and use the data in it for corresponding processing. In this way, we realize the transfer and use of custom objects.

Guess you like

Origin blog.csdn.net/QYgujingjing/article/details/132090848