Serialization of entity classes - Serializable and Parcelable

Table of contents

what is serialization

Why serialization is needed

way of serialization

example

Usage of Serializable:

Usage of Parcelable:

what is serialization

Data serialization refers to converting the object class developed by our program into the smallest unit of computer storage, a sequence of bytes.

The deserialization of data refers to converting the byte sequence in the computer into the object entity class we are developing.

Why serialization is needed

         For example, in the Java program development process, we declare a Person object, including (name, height, gender, occupation) and other attributes. When our program is executed and the Person attribute is assigned, this object exists in the memory, and the data in the memory After the power is turned off or the program ends, the data will be lost. In order to prevent the data from being lost, we can store it in the external storage of the computer in a serialized manner, and then access it from the outside when it is needed next time. The serialization method greatly improves the efficiency of data transmission . It also provides the possibility for persistent storage of data .

way of serialization

Java:Serializable

Android:Parcelable,

1: Rewrite the writetoParcel(in:Parcel,flag:Int) and describeContents() methods

2: Create the internal static attribute CREATOR, implement the Parcelable.Creator<T>() interface, and implement the createFromParcel and newArray methods

The ide is generally generated by itself, and we need to combine business supplementary attributes.

To prevent Android serialization from failing and failing to get values, ensure that the order and number of attributes in the constructor are consistent with those of writetoParcel

Principle: Map your object into a Parcel object through writeToParcel, and then map the Parcel object into your object through createFromParcel. Parcel can also be regarded as a stream, write objects into the stream through writeToParcel, and read objects from the stream through createFromParcel, but this process requires you to implement, so the order of writing and reading must be consistent

the difference:

Java's Serializabel interface is simple to use, but the efficiency is low, and a large number of temporary objects will be generated during use, causing GC.

Android's Parcelable interface needs to rewrite the method, which is more suitable for more complex data and has higher efficiency. The principle is that the Parcelable interface will decompose the object into data types that can be passed by the intent.

example

Usage of Serializable:

The entity class Student implements the Serializable interface

data class Student(val name:String):Serializable{
    var height:Float = 0.0f
    var age:Int = 0
    var sex:Int = 0

    override fun toString(): String {
        return "Student(name='$name', height=$height, age=$age, sex=$sex)"
    }
}

 In A Activity, it can be passed through intent's putExtra()

            val zs = Student("zhangsan")
            zs.height =152.5f 
            zs.age = 16
            zs.sex=1
            val intent = Intent(this,MainActivity2::class.java)
            intent.putExtra("data",zs)
            startActivity(intent)

 In Activity B, use getSerializableExtra() to convert to an object for receiving and using

        val zhangsan = intent.getSerializableExtra("student") as Student
        println("student name:${zhangsan.name}-age:${zhangsan.age}-height:${zhangsan.height}")

Usage of Parcelable:

Entity class Person

1: Implement the Parcelable interface, rewrite writeToPalcel(), describeContents()

2: Instantiate the static internal object CREATOR and implement the Parcelable.Creator<T>() interface

data class Person(val type:Int):Parcelable {

    var name = ""
    var age = 0


    constructor(parcel: Parcel) : this
        (type = parcel.readInt()) {
            //构造方法的变量及顺序应该和writeToParcel保持一致,不可不写
             name = parcel.readString().toString()
             age = parcel.readInt()
    }


    override fun writeToParcel(parcel: Parcel, flags: Int) {
        parcel.writeInt(type)
        parcel.writeString(name)
        parcel.writeInt(age)
    }

    override fun describeContents(): Int {
        return 0
    }

    override fun toString(): String {
        return "Person(type=$type, name='$name', age=$age)"
    }

    companion object CREATOR : Parcelable.Creator<Person> {
        override fun createFromParcel(parcel: Parcel): Person {
            return Person(parcel)
        }

        override fun newArray(size: Int): Array<Person?> {
            return arrayOfNulls(size)
        }
    }


}

In A Activity, pass the entity class object through bundle's putParcelable()

    val zs = Person(1)
    zs.name = "zhangsan"
    zs.age = 16
    val intent = Intent(this,MainActivity2::class.java)
    val bundle = Bundle()
    bundle.putParcelable("person",zs)
    intent.putExtra("data",bundle)
    startActivity(intent)

In B Activity, receive and use through bundle's getParcelableExtra<T>()

  val data = intent.getBundleExtra("data")
        val person = data?.getParcelable<Person>("person")
        if (person != null)
            println("name:${person.name},age:${person.age}")

 Serialization of Java-List collections and array types:

public class bean implements Parcelable {

    private List<DataBean> data;
    private int errorCode;
    private String errorMsg;
//    private int[] numberArray;

    protected bean(Parcel in) {
        //List集合写法
        data = in.readArrayList(DataBean.class.getClassLoader());
        errorCode = in.readInt();
        errorMsg = in.readString();
        //int[]数组写法
//        numberArray = in.createIntArray();
    }

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

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

    public List<DataBean> getData() {
        return data;
    }

    public void setData(List<DataBean> data) {
        this.data = data;
    }

    public int getErrorCode() {
        return errorCode;
    }

    public void setErrorCode(int errorCode) {
        this.errorCode = errorCode;
    }

    public String getErrorMsg() {
        return errorMsg;
    }

    public void setErrorMsg(String errorMsg) {
        this.errorMsg = errorMsg;
    }

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

    @Override
    public void writeToParcel(Parcel dest, int flags) {
        dest.writeList(data);
        dest.writeInt(errorCode);
        dest.writeString(errorMsg);
//        dest.writeIntArray(numberArray);
    }

    public static class DataBean implements  Parcelable{
        private String desc;
        private int id;
        private String imagePath;
        private int isVisible;
        private int order;
        private String title;
        private int type;
        private String url;

        protected DataBean(Parcel in) {
            desc = in.readString();
            id = in.readInt();
            imagePath = in.readString();
            isVisible = in.readInt();
            order = in.readInt();
            title = in.readString();
            type = in.readInt();
            url = in.readString();
        }

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

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

        public String getDesc() {
            return desc;
        }

        public void setDesc(String desc) {
            this.desc = desc;
        }

        public int getId() {
            return id;
        }

        public void setId(int id) {
            this.id = id;
        }

        public String getImagePath() {
            return imagePath;
        }

        public void setImagePath(String imagePath) {
            this.imagePath = imagePath;
        }

        public int getIsVisible() {
            return isVisible;
        }

        public void setIsVisible(int isVisible) {
            this.isVisible = isVisible;
        }

        public int getOrder() {
            return order;
        }

        public void setOrder(int order) {
            this.order = order;
        }

        public String getTitle() {
            return title;
        }

        public void setTitle(String title) {
            this.title = title;
        }

        public int getType() {
            return type;
        }

        public void setType(int type) {
            this.type = type;
        }

        public String getUrl() {
            return url;
        }

        public void setUrl(String url) {
            this.url = url;
        }

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

        @Override
        public void writeToParcel(Parcel dest, int flags) {
            dest.writeString(desc);
            dest.writeInt(id);
            dest.writeString(imagePath);
            dest.writeInt(isVisible);
            dest.writeInt(order);
            dest.writeString(title);
            dest.writeInt(type);
            dest.writeString(url);
        }
    }

Guess you like

Origin blog.csdn.net/qq_34123324/article/details/131324987