getParcelable()返回具有Parcelable对象的null数据成员的对象

时间:2016-05-28 15:18:10

标签: android android-intent android-activity parcelable

我正在关于Udacity(最终项目第一阶段)的这门课程,我需要制作一个热门电影应用程序。 一切都很好,但目前我无法将Movie对象传递给我的DetailsActivity。 Movie对象是Parcelable。

    public class Movie implements Parcelable{

    int id;
    String original_title;
    String poster_path;
    String overview;
    String backdrop_path;
    String vote_average;
    String release_date;

    public Movie(String _original_title, String _poster_path,
                 String _overview, String _backdrop_path,
                 String _vote_average, String _release_date, int _id){
        this.original_title = _original_title;
        this.id = _id;
        this.overview = _overview;
        this.poster_path = _poster_path;
        this.backdrop_path = _backdrop_path;
        this.vote_average = _vote_average;
        this.release_date = _release_date;
    }

    protected Movie(Parcel in) {
        id = in.readInt();
        original_title = in.readString();
        overview = in.readString();
        poster_path = in.readString();
        backdrop_path = in.readString();
        vote_average = in.readString();
        release_date = in.readString();
    }

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

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

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

    @Override
    public void writeToParcel(Parcel dest, int flags) {
        dest.writeString(original_title);
        dest.writeString(overview);
        dest.writeString(poster_path);
        dest.writeString(backdrop_path);
        dest.writeString(vote_average);
        dest.writeString(release_date);
        dest.writeInt(id);
    }
}

我正在使用以下代码在活动之间发送和检索数据。

MainActivityFragment.java

Movie mData = mMovieAdapter.getItem(position);
            Log.d("Backdrop Path", mData.backdrop_path+""); // Backdrop Path : http://image.tmdb.org/t/p/w185/m5O3SZvQ6EgD5XXXLPIP1wLppeW.jpg

            Bundle movieData = new Bundle();
            movieData.putParcelable(KEY_DETAIL, mData);

            Intent intent = new Intent(getActivity(), MovieDetailActivity.class);
            intent.putExtras(movieData);
            startActivity(intent);

MovieDetailActivityFragment.java

Bundle data = getActivity().getIntent().getExtras();
    if(data != null)
        movie = data.getParcelable(KEY_DETAIL);  //Movie object

    Log.d("Loading Image", movie.backdrop_path+"");  // Loading Image : null

所以根据日志,我确信被捆绑的Movie对象有数据。但是当我在另一个类中检索对象时,该对象不是null,而是数据成员。

1 个答案:

答案 0 :(得分:0)

对我来说,解决方案是改变读/写方法,以相同的顺序读/写每个对象。

此致