自定义的数据类型继承Serializable接口可是使对象序列化,我用来作为Activity间传递对象使用。
Utils.start_Activity(getActivity(),GameFriendDetailsActivity.class ,(Game)adapter.getItem(position));
Utils.java文件中start_Activity函数实现如下:
public static void start_Activity(Activity activity, Class<?> cls,
Game game) {
Intent intent = new Intent();
intent.setClass(activity, cls);
Bundle bundle = new Bundle();
bundle.putSerializable("Game",game);
intent.putExtras(bundle);
activity.startActivity(intent);
activity.overridePendingTransition(R.anim.push_left_in,
R.anim.push_left_out);
}
Game.java如下,成员变量是Team类型的list
public class Game implements Serializable {
private List<Team> game;
}
Team.java如下,成员变量是Friend类型的list
public class Team implements Serializable {
private List<Friend> team;
}
Friend.java类型如下,成员变量为正常的String或者Int类型
public class Friend implements Serializable, IFilterModel {
private String userId;
private String nickname;
private String nicknamePinyin;
private String portrait;
private String signature;
private String position;
private char searchKey;
private String sortLetters;
private Resource portraitResource;
private boolean isSelected = false;
private boolean isAdd = false;
}
总的逻辑是多个Friend组成Team,多个Team组成Game,每一个数据类型都要继承Serializable接口,不然在Activity中传递Friend对象时会发生如下错误:
FATAL EXCEPTION: main
Process: com.xxx.xx, PID: 11475
java.lang.RuntimeException: Parcelable encountered IOException writing serializable object (name = com.ykh.model.Game)
在使用了Utils.start_Activity( )方法传递了Game对象后,使用如下方法在目标Activity中获取由上级Activity传递的Game对象,完成Activity间的数据传递。
Intent intent = this.getIntent();
final Game game = (Game) intent.getSerializableExtra("Game");