getParcelableExtra在NullPointerException中返回

时间:2018-04-01 23:57:45

标签: java android

我正在尝试使用一个意图打开来自Mainactivity的DetailActivity,该意图将一个实现Parcelable的类对象作为额外的。在调用putExtra之前,我确实检查过对象是否有正确的数据。堆栈指向调用readList。

MainActivity.java

    movieViewAdapter =  new MovieViewAdapter(new ArrayList<Movies>(), new MovieViewAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(Movies movie) {
                Intent intent = new Intent(MainActivity.this,DetailActivity.class);
                intent.putExtra("thisMovie",movie);
                startActivity(intent);
            }
        });

这将打开DetailsActivity.java

@Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.detail_main);
        ButterKnife.bind(this);
        // Line 52
        Movies movie =  (Movies) getIntent().getParcelableExtra("thisMovie");
        .....
        .....           
    }

我得到以下错误:

Caused by: java.lang.NullPointerException: Attempt to invoke interface method 'boolean java.util.List.add(java.lang.Object)' on a null object reference
at android.os.Parcel.readListInternal(Parcel.java:3177)
at android.os.Parcel.readList(Parcel.java:2178)
at com.example.android.popularmoviesstage1.Models.Movies$1.createFromParcel(Movies.java:73)
at com.example.android.popularmoviesstage1.Models.Movies$1.createFromParcel(Movies.java:56)
at android.os.Parcel.readParcelable(Parcel.java:2851)
at android.os.Parcel.readValue(Parcel.java:2745)
at android.os.Parcel.readArrayMapInternal(Parcel.java:3114)
at android.os.BaseBundle.initializeFromParcelLocked(BaseBundle.java:273)
at android.os.BaseBundle.unparcel(BaseBundle.java:226)
at android.os.Bundle.getParcelable(Bundle.java:939)
at android.content.Intent.getParcelableExtra(Intent.java:7167)
at com.example.android.popularmoviesstage1.Activities.DetailActivity.onCreate(DetailActivity.java:52)

这是我对Movies.java的实现

public final static Parcelable.Creator<Movies> CREATOR = new Creator<Movies>() {
        @SuppressWarnings({
                "unchecked"
        })
        public Movies createFromParcel(Parcel in) {
            Movies instance = new Movies();
            ....
            ....
            //Line 73
            in.readList(instance.genreIds, (java.lang.Integer.class.getClassLoader()));
            ....
            ....
            return instance;
        }
        public Movies[] newArray(int size) {
            return (new Movies[size]);
        }
};

1 个答案:

答案 0 :(得分:0)

你使用Parcelable的插件来生成POJO。完美适合我。 该插件可在Android Studio插件库中使用。