Object transfer between activities Implementation tutorial, Activity tutorial
To transfer objects between two activities, the object must be serialized. There are two methods to serialize an object in android, one is to implement the Serializable interface, which is very simple, just declare it. However, there is a special serialization method in android, that is, implementing the Parcelable interface. The serialization efficiency of this method is higher than implementing the Serializable interface. However, the Serializable interface is too convenient. Therefore, it is a good choice to implement this interface in some cases.
The following uses serialization of objects in my User class as an example:
Method 1: implement the Serializable interface, which is included in Java and can be directly implemented, convenient and fast:
public class User implements Serializable { private String name; private int age; private String work; public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public String getWork() { return work; } public void setWork(String work) { this.work = work; } public User(String name, int age, String work) { this.name = name; this.age = age; this.work = work; } @Override public String toString() { return name+":"+age+":"+work; }}Method 2: This is a serialization method specific to Android, And the serialization efficiency is higher than the Serializable interface provided by java.
public class User implements Parcelable { private String name; private int age; private String work; public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public String getWork() { return work; } public void setWork(String work) { this.work = work; } public User(String name, int age, String work) { this.name = name; this.age = age; this.work = work; } @Override public String toString() { return name+":"+age+":"+work; } protected User(Parcel in) { name = in.readString(); age = in.readInt(); work = in.readString(); } @Override public int describeContents() { return 0; } @Override public void writeToParcel(Parcel dest, int flags) { Bundle bundle = new Bundle(); bundle.putString("name",name); bundle.putInt("age",age); bundle.putString("work",work); dest.writeBundle(bundle); } public static final Creator
CREATOR=new Creator
() { @Override public User createFromParcel(Parcel source) { Bundle bundle = source.readBundle(); return new User(bundle.getString("name"),bundle.getInt("age"),bundle.getString("work")); } @Override public User[] newArray(int size) { return new User[size]; } };}
Select Parcelable for memory serialization and Serializable for storage to devices or network transmission.