在枚举上写入 Parcelable 会使应用程序崩溃

dest.writeParcelable(department, flags);当我通过意图包裹对象时,这条线导致应用程序崩溃。


当我评论该行时,应用程序会通过,但当然我没有部门价值。


public class User implements Parcelable {


    public String id;

    public String name;

    public String email;

    public Department department;


    // other implementations of Parcelable 


protected UserVO(Parcel in) {

    id = in.readString();

    name = in.readString();

    email = in.readString();

    department = in.readParcelable(Department.class.getClassLoader());

}



    @Override

    public void writeToParcel(Parcel dest, int flags) {

        dest.writeString(id);

        dest.writeString(name);

        dest.writeString(email);

        dest.writeParcelable(department, flags); // crashes

    }

}

部门枚举


public enum Department implements Parcelable {


    SALES("Sales", 1),

    HR("Human Resources", 2),

    SHIPPING("Shipping", 3),


    public final String name;

    public final int ordinal;


    Department(String name, int ordinal) {

        this.name = name;

        this.ordinal = ordinal;

    }


    Department(Parcel in) {

        name = in.readString();

        ordinal = in.readInt();

    }


    public static final Creator<Department> CREATOR = new Creator<Department>() {

        @Override

        public Department createFromParcel(Parcel in) {

            return Department.valueOf(in.readString()); // crash

            //return new DeptEnum(in); // android studio generated code but has error: enum types may not be instantiated

        }


        @Override

        public Department[] newArray(int size) {

            return new Department[size];

        }

    };


    @Override

    public int describeContents() {

        return 0;

    }


    @Override

    public void writeToParcel(Parcel parcel, int i) {

        parcel.writeString(name);

        parcel.writeInt(ordinal);

    }

}

错误

没有枚举常量 Department.Sales

我从这个答案中得到了帮助return Department.valueOf(in.readString());


偶然的你
浏览 120回答 1
1回答

温温酱

您不需要打包序号。单独对名称执行 valueOf 就可以了但是,valueOf 的参数必须与枚举定义的名称完全匹配。例如,这适用于销售和运输,但不适用于人力资源Department.valueOf(in.readString().toUpperCase());您需要的解决方案是循环并将Department.values()值的每个名称字段与 in.readString() 结果进行比较如何从 Java 枚举的 String 值中查找它?或者您可以像这样使用序数,尽管您正在复制序数信息并且必须保证枚举具有连续的数字 return Department.values()[in.readInt() - 1]
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java