Android使用Parcelable传递boolean、String、Class、List、Enum类型数据

最近有一个需求是从ActivityA往ActivityB传递一些用户数据,内容较多,使用Parcelable对象实现序列化,基本数据类型中除了boolean之外,其他的几个用String代表了。重点看一下 boolean,String,Class,List,Enum 类型的传递。上代码。

首先这个是enum类型的类:

public enum MyType implements Parcelable{
    Man,Woman,Unknown;

    @Override
    public int describeContents() {
        return 0;
    }

    @Override
    public void writeToParcel(Parcel dest, int flags) {
        dest.writeInt(ordinal());
    }

    public static final Creator CREATOR = new Creator() {
        @Override
        public MyType createFromParcel(final Parcel source) {
            return MyType.values()[source.readInt()];
        }

        @Override
        public MyType[] newArray(final int size) {
            return new MyType[size];
        }
    };
}

要传递的就是这个类:

public class AccountInfo implements Parcelable {
    private boolean isNewUser;//boolean类型
    private String name;//String类型
    private UserCardInfo userCard;//对象类型
    private List bankInfos;//List类型
    private MyType myType;//enum类型
    protected AccountInfo(Parcel in) {
        isNewUser = in.readByte() != 0;
        name = in.readString();
        userCard = in.readParcelable(getClass().getClassLoader());
        Parcelable[] proPars = in.readParcelableArray(getClass().getClassLoader());
        bankInfos = Arrays.asList(Arrays.asList(proPars).toArray(new BankCard[proPars.length]));
        //enum无法直接传递,只能做一下转换。
        String myTypeString = in.readString();
        if (myTypeString != null) {
            this.myType = MyType.valueOf(myTypeString);
        }
    }
    public static final Creator CREATOR = new Creator() {
        @Override
        public AccountInfo createFromParcel(Parcel in) {
            return new AccountInfo(in);
        }

        @Override
        public AccountInfo[] newArray(int size) {
            return new AccountInfo[size];
        }
    };

    @Override
    public int describeContents() {
        return 0;
    }

    @Override
    public void writeToParcel(Parcel dest, int flags) {
        dest.writeByte((byte) (isNewUser ? 1 : 0));
        dest.writeString(name);
        dest.writeParcelable(userCard, flags);
        dest.writeParcelableArray(bankInfos.toArray(new BankCard[bankInfos.size()]), flags);
        dest.writeString(myType == null ? null : myType.name());
    }

    /**..setter & getter..**/
}

传递时代码:

Intent intent = new Intent(activity, AccountActivity.class);
Bundle bundle = new Bundle();
bundle.putParcelable(Manager.KEY_ACCOUNTINFO, dMAccountInfo);
intent.putExtra(OpenActivity.KEY_OPEN,bundle);
activity.startActivity(intent);

需要注意的是在接收List数据时,需要使用如下代码来获取:

dm = bundle.getParcelable(KEY_ACCOUNTINFO);
ArrayList<BankCard> data = new ArrayList<>(dm.getBankInfos());

否则会报java.lang.ClassCastException: java.util.Arrays$ArrayList cannot be cast to java.util.ArrayList

你可能感兴趣的:(Android开发问题)