1

我在我的应用程序中使用意图操作传递 parcelable 值时收到 BadParcelableException。如何传递可打包的值并在另一个类中检索它们?

下面是我的代码:

public MySample mySample;

  public class MySample implements Parcelable {
        private boolean galleryPicker = false;
        private boolean gallery = false;
        private ImageButton button;
        private View view;

        public ImageButton getButton() {
            return button;
        }

        public void setPostButtonItem(ImageButton button) {
            this.button= button;
        }
        @Override
        public void writeToParcel(Parcel dest, int flags) {
            dest.writeStringArray(new String[] {});
        }

        public int describeContents(){
            return 0;
        }

意图行动:

public class Popup// (Actually I call this class from my BaseActivity)
{
    public Popup(Activity activity,ActionBar action)
    {
        MySample mySample= new MySample();
        sample.data.setStatus=true;
        no= (TextView) popupView.findViewById(R.id.no);
        yes= (TextView) popupView.findViewById(R.id.yes);
        mySample.gallery = true;
        mySample.count = true;
        context = getContext();
        Intent intent = new Intent(context, NextActivity.class);
        intent.putExtra("sample", mySample);
        context.startActivity(intent);
    }
}

在另一个类中提取意图:

private MySample mySample;
Bundle data = getIntent().getExtras();
this.mySample= data.getParcelable("sample");

例外:

引起:android.os.BadParcelableException:Parcelable 协议需要一个 Parcelable.Creator 对象,在类上称为 CREATOR

4

1 回答 1

2

尝试这个

 public class MySample implements Parcelable {

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

        public MySample[] newArray(int size) {
            return new MySample[size];
        }
    };
    private boolean galleryPicker = false;
    private boolean gallery = false;

    public MySample(Parcel in) {
        boolean[] temp = new boolean[2];
        in.readBooleanArray(temp);
        galleryPicker = temp[0];
        gallery = temp[1];
    }

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

    @Override
    public void writeToParcel(Parcel dest, int flags) {
        dest.writeBooleanArray(new boolean[]{galleryPicker, gallery});
    }
}
于 2015-03-05T13:17:19.467 回答