如何在android中发送parcelable类

时间:2016-06-08 16:49:45

标签: android bundle parcelable

我在SO上经历了很多解决方案。但它们都不适合我。我只是尝试使用

将一个parcelable类从一个Activity发送到另一个Activity
Bundle bundle = new Bundle();
bundle.putParcelable("parcelableMovie", (Parcelable) movieItemArrayList.get(position));
Intent intent = new Intent(BaseActivity.this, MovieDetailActivity.class);
intent.putExtras(bundle);
startActivity(intent);

我在 MovieDetailActivity.onCreate 中添加了一个调试器点,并且附加功能没有任何内容。我试过用几种方法改变我的代码。与投射MovieItem而不是Parcelable

一样

MovieDetailActivity.class

Bundle extras = getIntent().getExtras();

if (extras != null) {
    //movieItem = (MovieItem) getIntent().getParcelableExtra("name_of_extra");

    movieItem = (MovieItem) getIntent().getParcelableExtra("parcelableMovie");

    //movieItem = (MovieItem) extras.getParcelable("parcelableMovie");
    if (movieItem != null) {
        movieTitle.setText(movieItem.getName());
        releasingDate.setText(movieItem.getReleaseDate());
    }
}

但是movieItem始终显示为空

修改 MovieItem.java

public class MovieItem implements Parcelable  {

    private String name;
    private String rating;
    private String releaseDate;
    private int image;

    public MovieItem(String name, String rating, String releaseDate, int image) {
        this.name = name;
        this.rating = rating;
        this.releaseDate = releaseDate;
        this.image = image;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getRating() {
        return rating;
    }

    public void setRating(String rating) {
        this.rating = rating;
    }

    public String getReleaseDate() {
        return releaseDate;
    }

    public void setReleaseDate(String releaseDate) {
        this.releaseDate = releaseDate;
    }

    public int getImage() {
        return image;
    }

    public void setImage(int image) {
        this.image = image;
    }

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

    @Override
    public void writeToParcel(Parcel dest, int flags) {
        dest.writeString(this.name);
        dest.writeString(this.rating);
        dest.writeString(this.releaseDate);
        dest.writeInt(this.image);
    }

    protected MovieItem(Parcel in) {
        this.name = in.readString();
        this.rating = in.readString();
        this.releaseDate = in.readString();
        this.image = in.readInt();
    }

    public static final Creator<MovieItem> CREATOR = new Creator<MovieItem>() {
        @Override
        public MovieItem createFromParcel(Parcel source) {
            return new MovieItem(source);
        }

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

0 个答案:

没有答案