Intent 传递对象的两种方法

一:通过Serializable接口


public class User implements Serializable {

private static final long serialVersionUID = 2923551487809150124L;
public int userId;
public String name;
public boolean isMale;
@Override
public String toString() {
// TODO Auto-generated method stub
return "userId="+userId+";name="+name+";isMale="+isMale;
}
}

Activity中传递对象
User user = new User();
user.name="liming";
user.userId=1;
user.isMale=true;
Intent intent = new Intent(MainActivity.this,SecondActivity.class);
Bundle mBundle = new Bundle();
mBundle.putSerializable("user",user);
intent.putExtras(mBundle);
startActivity(intent);
Activity中接收对象
User user = (User)getIntent().getSerializableExtra("user");

二:通过Parcelable接口实现

public class NewUser implements Parcelable {

public int userId;
public String userName;
public boolean isMale;

public NewUser() {
}

public NewUser(int userId, String userName, boolean isMale) {
this.userId = userId;
this.userName = userName;
this.isMale = isMale;
}

@Override
public int describeContents() {
// TODO Auto-generated method stub
return 0;
}

@Override
public void writeToParcel(Parcel out, int flags) {
// TODO Auto-generated method stub
out.writeInt(userId);
out.writeString(userName);
out.writeInt(isMale ? 1 : 0);
}

public static final Parcelable.Creator<NewUser> CREATOR = new Parcelable.Creator<NewUser>() {
public NewUser createFromParcel(Parcel in) {
return new NewUser(in);
}

public NewUser[] newArray(int size) {
return new NewUser[size];
}
};

private NewUser(Parcel in) {
userId = in.readInt();
userName = in.readString();
isMale = in.readInt() == 1;

}

@Override
public String toString() {
// TODO Auto-generated method stub
return "userId=" + userId + ";name=" + userName + ";isMale=" + isMale;
}

}
Activity中传递对象
NewUser user = new NewUser();
user.isMale = false;
user.userId = 1;
user.userName = "jack";
Intent mintent = new Intent(SecondActivity.this,ThirdActivity.class);
Bundle mBundle = new Bundle();
mBundle.putParcelable("newuser",user);
mintent.putExtras(mBundle);
startActivity(mintent);
Activity中接收对象
NewUser user = (NewUser)getIntent().getParcelableExtra("newuser");

总结: Serializable 是java中序列号的接口,使用简单但开销较大,序列号和反序列号底层都需要大量的I/O操作。而Parcelable 是Android中的序列化方式,使用起来麻烦点,但效率很高。

建议:在内存序列化时候使用Parcelable,如果将对象序列化到存储设备或者将序列化对象通过网络传输使用Serializable。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值