在Activity之间传递数据时有两种方式
1、Serializable方式:序列化方式,即将一个对象转化为可存储或者是可传输的内容,相应的将数据从内存卡中读取出来是反序列化方式
2、Parcelable方式:将一个完整的对象分解成每一个都可以用Intent传输的对象。
使用Serializable传递数据
Intent intent = new Intent(MainActivity.this, SecondActivity.class);
//传递boolean类型
intent.putExtra("boolean", true);
//传递字符串类型
intent.putExtra("String", "String");
//传递整型
intent.putExtra("Integer", 0);
//有时候需要同时传递多个数据,这时我们可以使用一个Bundle将其封装起来
Bundle bundle = new Bundle();
bundle.putString("s", "s");
//传递实体类时,必须实现Serializable接口
bundle.putSerializable("man", new Man("jack", 10));
//传递字符型
bundle.putChar("char", 'c');
//将bundle放入到intent中
intent.putExtras(bundle);
//启动activity
startActivity(intent);
//获取数据是也比较简单,对应类型就行了:
String data = getIntent().getStringExtra("String");
//获取到Bundle对象
Bundle extras = getIntent().getExtras();
//再根据bundle中 类型获取到对应的数据
使用Parceleable传递数据
public class Person implements Parcelable {
private String name;
private int age;
private int id;
public Person(String name, int age, int id) {
this.name = name;
this.age = age;
this.id = id;
}
//读取数据:什么类型对应其相应的类型
protected Person(Parcel in) {
name = in.readString();
age = in.readInt();
id = in.readInt();
}
public static final Creator<Person> CREATOR = new Creator<Person>() {
@Override
public Person createFromParcel(Parcel in) {
return new Person(in);
}
@Override
public Person[] newArray(int size) {
return new Person[size];
}
};
@Override
public String toString() {
return "name:" + name + "\t" + "age:" + age + "\t id:" + id;
}
@Override
public int describeContents() {
return 0;
}
//往Parcelable中写入相应的数据
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(name);
dest.writeInt(age);
dest.writeInt(id);
}
}读取方式都是相同的。