android: activity之间传递复杂数据类型[使用Serializable序列化或者Parcelable序列化]


1. 实现Serializable接口  比较简单直接实现即可

public class Student implements Serializable{
	private static final long serialVersionUID = 1L;
	public int id;
	public String name;

}

2. 实现Parcelable接口  需要在类中添加一个静态成员变量 CREATOR,这个变量需要继承 Parcelable.Creator 接口。

	class Teacher implements Parcelable{

		private int id;
		private String name;
		
	    public Teacher(int id, String name) {  
	        this.id = id;  
	        this.name = name;  
	    }  
	    
		@Override
		public int describeContents() {
			return 0;
		}

		@Override
		public void writeToParcel(Parcel dest, int flags) {
			dest.writeInt(id);  
	        dest.writeString(name);  
		}
	    public static final Parcelable.Creator<Teacher> CREATOR = new Parcelable.Creator<Teacher>() {  
	    	  
	        @Override  
	        public Teacher createFromParcel(Parcel source) {  
	            Teacher teacher = new Teacher(source.readInt(), source.readString());  
	            return teacher;  
	        }  
	 
	        @Override  
	        public Teacher[] newArray(int size) {  
	            return null;  
	        }  
	    }; 
		
	}

发送数据:

 // Serializable序列化传送  
            ArrayList<Student> list = new ArrayList<Student>();  
            Student student = new Student(1, "Jim");  
            list.add(student);  
            Intent intent = new Intent(this, SecondActivity.class);  
            intent.putExtra("STUDENT_INFO", list);  
            startActivity(intent);  

 // parcel序列化传送  
            ArrayList<Teacher> list = new ArrayList<Teacher>();  
            Teacher teacher1 = new Teacher(1, "techaer1");  
            list.add(teacher1);  
            Intent intent = new Intent(this, SecondActivity.class);  
            intent.putExtra("TEACHER_INFO", list);  
            startActivity(intent);  

接收数据:

        Intent intent = getIntent();  
        // serializable  
         ArrayList<Student> list = (ArrayList<Student>) intent.getSerializableExtra("STUDENT_INFO"); 

        // parcelble  
        ArrayList<Teacher> list = intent.getParcelableArrayListExtra("TEACHER_INFO");  


你可能感兴趣的:(android: activity之间传递复杂数据类型[使用Serializable序列化或者Parcelable序列化])